[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只会继续迭代。
当前回答
简短回答:用于。。。为此中断或更改代码以避免中断forEach。不要使用.some()或.every()来模拟。。。打破重写代码以避免。。。中断循环,或用于。。。打破每次你使用这些方法。。。上帝杀死了小猫。
长答案:
.some()和.every()都返回布尔值,如果有任何元素的传递函数返回true,.some(返回true,如果有元素的传递的函数返回false,则every返回false。这就是函数的含义。使用函数来实现它们并不意味着什么,这比使用表来布局而不是CSS要糟糕得多,因为这会让所有阅读代码的人感到沮丧。
此外,使用这些方法的唯一可能方法是。。。break替代方法是产生副作用(在.some()回调函数之外更改一些vars),这与for。。。打破
因此,使用.some()或.every()作为。。。断环替代方案并没有副作用,这对。。。打破,这是令人沮丧的,所以这不是更好的。
您可以随时重写代码,这样就不需要。。。打破您可以使用.filter()过滤数组,也可以使用.slice()等拆分数组,然后使用.forEach()或.map()处理该部分数组。
其他回答
如果您想使用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函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。
我使用return false,这对我有用。
考虑使用jquery的each方法,因为它允许在回调函数中返回false:
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Lodash库还提供了takeWhile方法,可以与map/reduce/fold等链接:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
使用array.prototype.every函数,它为您提供了中断循环的实用程序。请参阅Mozilla开发者网络上的Javascript文档示例
我为此使用了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
}
//