[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只会继续迭代。
当前回答
没有内置的功能可以为Each进行破解。要中断执行,必须抛出某种异常。
var BreakException={};尝试{[1,2,3]对于每个(函数(el){控制台日志(el);如果(el==2)抛出BreakException;});}捕获(e){如果(e!==BreakException)抛出e;}
JavaScript异常并不漂亮。如果你真的需要打破传统的for循环,那么它可能更合适。
使用数组#some
而是使用Array#some:
[1,2,3]一些(函数(el){控制台日志(el);返回el==2;});
这之所以有效,是因为只要按数组顺序执行的任何回调返回true,就会立即返回true,从而缩短其余回调的执行。
有些,它的逆every(返回false时停止)和forEach都是ECMAScript第五版方法,需要在缺少它们的浏览器上添加到Array.prototype中。
使用数组#间隔
[1,2,3]每(v=>{如果(v>2){return false//“break”}控制台日志(v);return true//如果不中断,则必须返回true});
其他回答
这只是我想出的解决问题的方法。。。我很确定它解决了最初提问者的问题:
Array.prototype.each = function(callback){
if(!callback) return false;
for(var i=0; i<this.length; i++){
if(callback(this[i], i) == false) break;
}
};
然后您可以使用以下方法调用它:
var myarray = [1,2,3];
myarray.each(function(item, index){
// do something with the item
// if(item != somecondition) return false;
});
在回调函数中返回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函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。
如前所述,不能破坏.forEach()。
这里有一种使用ES6迭代器进行foreach的稍微更现代的方法。允许您在迭代时直接访问索引/值。
const array = ['one', 'two', 'three'];
for (const [index, val] of array.entries()) {
console.log('item:', { index, val });
if (index === 1) {
console.log('break!');
break;
}
}
输出:
item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!
链接
Array.prototype.entries()迭代器和发电机解构赋值
使用array.prototype.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例
如果迭代后不需要访问数组,可以通过将数组的长度设置为0来退出。如果您在迭代后仍然需要它,可以使用slice来克隆它。。
[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
或者使用克隆:
var x = [1,3,4,5,6,7,8,244,3,5,2];
x.slice().forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
这是一个比在代码中抛出随机错误更好的解决方案。