简体   繁体   中英

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

I need a way to check if an array only contains numbers. For example

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

whereas var b = [1,3,4,'a'] should give false

I tried forEach() function as

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

but since, forEach() iterates through every index in the array, and since every item for var a is a number, it unshifts to array every item it iterates. I need a way to only unshift "-" once if the whole array value is a number.

I also tried to do with 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';});

Try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM