代码之家  ›  专栏  ›  技术社区  ›  linezokode

如何检查数组中的类型?

  •  0
  • linezokode  · 技术社区  · 4 年前

    我需要告诉程序搜索一个数组(这意味着只有数字),如果它包含任何字符串元素。

    此外,数组由函数的参数组成。有人能帮忙吗?我想弄清楚这件事至少有一个小时了!这就是我目前所做的:

    const sumAll = function(…args){
      const newArray = Array.from(args)
      for(let i = 0; i < newArray.length; i++){
        if(newArray[i] === NaN){
        return “ERROR”
        }
      }
    }
    
    5 回复  |  直到 4 年前
        1
  •  0
  •   Jamiec    4 年前

    你在寻找函数 isNaN

    const sumAll = function(...args){
      const newArray = Array.from(args)
      for(let i = 0; i < newArray.length; i++){
        if(isNaN(newArray[i])){
          return "ERROR"
        }
      }
    }
    
    console.log(sumAll(1,2,3)) // no output - undefined
    
    console.log(sumAll(1,"two",3)) // error
        2
  •  0
  •   Anurag Vohra    4 年前
    let foundString = arrayWithPossiblyString.find(i=>isNaN(5-i));
    

    说明:

    1. 5.“a”是一个名词。
    2. isNaN函数可用于检查是否存在NaN
        3
  •  0
  •   Singh3y    4 年前

    你可以用 arguments 关键字来访问将作为参数传递给该特定函数的所有变量。此外,还可以使用isNaN函数来确定给定参数是否为数字。

    function check(){
        const arr = arguments
        for(const item of arr) {
            if(isNaN(item)){
                return "Error"
            }
        }
    }
    
    check(1, "Hello", "4")
    
        4
  •  0
  •   Alex    4 年前

    我建议使用 isNaN 功能:

    ...
    if(isNaN(newArray[i])) {
       return "ERROR";
    }
    
        5
  •  0
  •   Nina Scholz    4 年前

    你可以去看看 Array#some 拿着 isNaN 作为回拨。

    const sumAll = function(...args) {
        if (args.some(isNaN)) return "ERROR";
    }
    
    console.log(sumAll(1, 2, 3));     // undefined
    console.log(sumAll(1, "two", 3)); // ERROR
        6
  •  0
  •   Hardik Desai    4 年前
    const sampleErrorArr = [0, 1, 'two', 3, 4,]
    const sampleArr = [0, 1, 2, 3, 4]
    
    function sumAll(arr) {
        let sum = 0
        let hasNotNumber = true
        arr.forEach((item, index) => {
            if (typeof item === 'number') {
                let temp = sum + item
                sum = temp
            }
            else {
                hasNotNumber = false
            }
        })
    
        return hasNotNumber == true ? sum : "Error"
    }
    
    console.log(sumAll(sampleErrorArr)) // Error
    console.log(sumAll(sampleArr))// 10