检查数组中的所有值是否都是数字

check to see if all values inside an array is a number

本文关键字:是否 数字 数组 检查      更新时间:2023-09-26

我需要一种方法来检查数组是否只包含数字。例如

var a = [1,2,3,4] should pass and give true boolean
whereas var b = [1,3,4,'a'] should give false

我尝试了forEach()函数作为

a.forEach(function(item, index, array) {
    if(!isNaN(item)) {
        array.unshift("-");
    }
});  //console.log of this will give array a = ["-","-","-","-", 1,2,3,4]

,但是由于forEach()遍历数组中的每个索引,并且由于var a的每个项都是数字,因此它将迭代的每个项都平移到数组中。我需要一种方法,如果整个数组值是一个数字,只平移一次"-"。

我也试着用test()

var checkNum = /[0-9]/;
console.log(checkNum.test(a)) //this gives true 
console.log(checkNum.test(b)) // this also gives true since I believe test     
                              //only checks if it contains digits not every 
                              //value is a digit.

最简单的是使用Arrayevery函数:

var res = array.every(function(element) {return typeof element === 'number';});

试试这样:

var a = arr.reduce(function(result, val) {
   return result && typeof val === 'number';
}, true);

function areNumbers(arr) {
  document.write(JSON.stringify(arr) + ':')
  return arr.reduce(function(result, val) {
    return result && typeof val === 'number';
  }, true);
}
document.write(areNumbers([1, 2, 3, 4]) + '<br>');
document.write(areNumbers([1, 2, 3, '4']) + '<br>');

var filteredList = a.filter(function(item){ return !isNaN(+item) });

开头的+号将尝试将项目转换为数字,如果可以,它将不会过滤掉,例如:

var numbers = +"123"

console.log(numbers) //will print out 123 as numbers not as a string