[1,2,3].forEach(function(el) {
if(el === 1) break;
});
如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。
当前回答
引用Array.prototype.forEach()的MDN文档:
除此之外,无法停止或中断forEach()循环通过抛出异常。如果您需要这样的行为,.forEach()方法是错误的工具,请改用普通循环。如果要测试谓词的数组元素并需要布尔返回值,则可以改用every()或some()。
对于您的代码(在问题中),如@bobince所建议的,请改用Array.protocol.some()。它非常适合您的用例。
Array.pr原型.some()对数组中的每个元素执行一次回调函数,直到找到一个回调返回真值(当转换为布尔值时变为真)的元素。如果找到这样的元素,some()立即返回true。否则,some()返回false。回调仅对已赋值数组的索引调用;对于已删除或从未赋值的索引,不会调用它。
其他回答
引用Array.prototype.forEach()的MDN文档:
除此之外,无法停止或中断forEach()循环通过抛出异常。如果您需要这样的行为,.forEach()方法是错误的工具,请改用普通循环。如果要测试谓词的数组元素并需要布尔返回值,则可以改用every()或some()。
对于您的代码(在问题中),如@bobince所建议的,请改用Array.protocol.some()。它非常适合您的用例。
Array.pr原型.some()对数组中的每个元素执行一次回调函数,直到找到一个回调返回真值(当转换为布尔值时变为真)的元素。如果找到这样的元素,some()立即返回true。否则,some()返回false。回调仅对已赋值数组的索引调用;对于已删除或从未赋值的索引,不会调用它。
如果您想使用Dean Edward的建议并抛出StopIteration错误以跳出循环而不必捕获错误,则可以使用以下函数(最初来自此处):
// Use a closure to prevent the global namespace from be polluted.
(function() {
// Define StopIteration as part of the global scope if it
// isn't already defined.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
// The original version of Array.prototype.forEach.
var oldForEach = Array.prototype.forEach;
// If forEach actually exists, define forEach so you can
// break out of it by throwing StopIteration. Allow
// other errors will be thrown as normal.
if(oldForEach) {
Array.prototype.forEach = function() {
try {
oldForEach.apply(this, [].slice.call(arguments, 0));
}
catch(e) {
if(e !== StopIteration) {
throw e;
}
}
};
}
})();
上述代码将使您能够运行以下代码,而无需执行自己的try-catch子句:
// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
if(val == 2)
throw StopIteration;
alert(val);
});
需要记住的一点是,如果Array.prototype.forEach函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。
同意@bobince,支持。
此外,仅供参考:
Prototype.js有这样的功能:
<script type="text/javascript">
$$('a').each(function(el, idx) {
if ( /* break condition */ ) throw $break;
// do something
});
</script>
$break将由Prototype.js在内部捕获和处理,打破“each”循环,但不会产生外部错误。
有关详细信息,请参见Prototype.JS API。
jQuery也有一种方法,只需在处理程序中返回false,即可尽早中断循环:
<script type="text/javascript">
jQuery('a').each( function(idx) {
if ( /* break condition */ ) return false;
// do something
});
</script>
有关详细信息,请参见jQuery API。
您可以使用每种方法:
[1,2,3].every(function(el) {
return !(el === 1);
});
ES6
[1,2,3].every( el => el !== 1 )
对于旧浏览器支持使用:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
更多详情请点击此处。
考虑使用jquery的each方法,因为它允许在回调函数中返回false:
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Lodash库还提供了takeWhile方法,可以与map/reduce/fold等链接:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []