Array.prototype.every看起来是不同于你想要什么:
的每一个方法的每个元素出现一次执行提供的回调函数直到它找到一个回调返回一个falsy值的地方。如果找到这样的元素,则每个方法立即返回false。否则,如果回调函数为所有元素返回一个真值,则每个元素都返回true。仅对已分配值的数组索引调用回调;对于已删除或从未分配过值的索引,不会调用它。
var tableRows = [1, 2, 3, 4, 5, "word"];
var tableRows2 = [1, 2, 3, 4, 5];
var everyTest = tableRows.every(function(currentValue, index, array) {
return (typeof currentValue == "number")
});
var everyTest2 = tableRows2.every(function(currentValue, index, array) {
return (typeof currentValue == "number")
});
console.log(everyTest);
console.log(everyTest2);
你可能想用一个Array.prototype.forEach。可悲的是there is no way to break from a forEach short of throwing an exception,这听起来像你的困境。
var tableRows = [1, 2, 3, 4, 5, "words"];
var forEachTest = tableRows.forEach(function(currentValue, index, array) {
console.log(currentValue);
});
虽然forEach
没有break
,传统for
循环呢!
var tableRows = [1, 2, 3, 4, 5, "words", 6, 7, 8];
for (var i = 0; i < tableRows.length; i++) {
var current = tableRows[i];
if(typeof current != 'number')
break;
console.log(current);
}