[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只会继续迭代。
当前回答
在其他网站上找到此解决方案。您可以在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/
其他回答
同意@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。
我为此使用了nullhack,它试图访问null的属性,这是一个错误:
try {
[1,2,3,4,5]
.forEach(
function ( val, idx, arr ) {
if ( val == 3 ) null.NULLBREAK;
}
);
} catch (e) {
// e <=> TypeError: null has no properties
}
//
这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:
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();}});
const Book = {"Titles":[
{"Book3" : "BULLETIN 3"},
{"Book1" : "BULLETIN 1"},
{"Book2" : "BULLETIN 2"}
]}
const findbystr = function(str) {
Book.Titles.forEach(function(data) {
if (typeof data[str] != 'undefined') {
return data[str];
}
}, str)
}
book = findbystr('Book1');
console.log(book);