[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只会继续迭代。
当前回答
同意@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。
其他回答
使用array.prototype.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例
如果您想使用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函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。
这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
您可以使用每种方法:
[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;
};
}
更多详情请点击此处。
如果您需要根据数组中已经存在的元素的值进行中断(例如,如果中断条件不依赖于在为数组分配元素值后可能发生变化的运行时变量),您也可以使用slice()和indexOf()的组合,如下所示。
如果您需要在forEach到达“Apple”时中断,可以使用
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon
fruitsToLoop.forEach(function(el) {
// no need to break
});
如W3Schools.com中所述,slice()方法将数组中选定的元素作为新的数组对象返回。原始阵列将不会更改。
在JSFiddle中查看
希望这对某人有所帮助。