[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。回调仅对已赋值数组的索引调用;对于已删除或从未赋值的索引,不会调用它。
其他回答
这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
我提出的另一个概念是:
函数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();}});
在其他网站上找到此解决方案。您可以在try/catch场景中包装forEach。
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
try {
[1,2,3].forEach(function(el){
alert(el);
if(el === 1) throw StopIteration;
});
} catch(error) { if(error != StopIteration) throw error; }
此处提供更多详细信息:http://dean.edwards.name/weblog/2006/07/enum/
你可以按照下面的代码操作,这对我很有用:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});
如果您想保持forEach语法,这是一种保持其高效的方法(尽管不如常规for循环好)。立即检查一个变量,该变量是否知道您是否想要脱离循环。
此示例使用匿名函数来围绕forEach创建函数范围,您需要存储已完成的信息。
(函数(){var element=document.getElementById('打印结果');var done=假;[1,2,3,4].forEach(功能(项目){如果(完成){return;}var text=document.createTextNode(项);element.appendChild(文本);如果(项==2){done=真;回来}});})();<div id=“printed result”></div>
我的两分钱。