[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.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例
其他回答
我提出的另一个概念是:
函数forEach(数组,cb){var shouldBreak;函数_break(){shouldBreak=true;}for(var i=0,bound=array.length;i<bound;++i){if(shouldBreak){break;}cb(array[i],i,array,_break);}}//用途forEach([‘a’,‘b’,‘c’,‘d’,‘e’,‘f’],函数(char,i,array,_break){console.log(i,char);如果(i===2){_break();}});
使用array.prototype.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例
如前所述,不能破坏.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()迭代器和发电机解构赋值
这是一个for循环,但像forEach()一样在循环中维护对象引用,但可以中断。
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
你可以按照下面的代码操作,这对我很有用:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});