[英]check to see if all values inside an array is a number
我需要一種檢查數組是否僅包含數字的方法。 例如
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.
最簡單的方法是使用Array
的every
函數:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.