我需要一种方法来检查数组是否只包含数字.例如
var a = [1,2,3,4] should pass and give true boolean
whereas var b = [1,3,4,'a'] should give false
Run Code Online (Sandbox Code Playgroud)
我试过forEach()函数为
a.forEach(function(item, index, array) {
if(!isNaN(item)) {
array.unshift("-");
}
}); //console.log of this will give array a = ["-","-","-","-", 1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
但是,因为,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.
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用以下every功能Array:
var res = array.every(function(element) {return typeof element === 'number';});
Run Code Online (Sandbox Code Playgroud)