[英]JavaScript: simulating 'break' inside 'foreach' loop
What is the best way to implement a siulation of 'break' feature of a for-loop when you are iterating through an user/engine-defined function? 在通过用户/引擎定义的函数进行迭代时,实现for循环的“中断”功能隔离的最佳方法是什么?
foreach([0,1,2,3,4],function(n){
console.log(n);
if (n==2)
break;});
I've thought in implementing foreach in a way that would break when the function returned 'false' - but I would like to hear thoughts on how that is normally done. 我曾考虑过以一种在函数返回“ false”时会中断的方式实现foreach的方法-但我想听听有关如何正常完成操作的想法。
return
ing false
is the most common way to do it. return
false
是最常见的方法。 That's what jQuery's iterator function .each()
does: 这就是jQuery的迭代器函数.each()
作用:
We can break the $.each() loop at a particular iteration by making the callback function return false . 通过使回调函数返回false,可以在特定迭代中中断$ .each()循环。 Returning non-false is the same as a continue statement in a for loop; 返回非false与for循环中的continue语句相同; it will skip immediately to the next iteration. 它将立即跳至下一个迭代。
And its very simplified implementation: 及其非常简化的实现:
each: function( object, callback ) {
var i = 0, length = object.length,
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; // break if false is returned by the callback
value = object[++i] ) {}
return object;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.