简单的答案是将return 语句放入forEach 循环中,就像@nnnnnn 所说的那样,
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
但如果你想深入回答这个问题,那就跟我来吧。
假设您不知道forEach 循环的实现,那么请看一下forEach 循环的以下实现,这正是ECMA-262 第5 版中为forEach 循环指定的那个。
来源 Array.prototype.forEach() - JavaScript | MDN
if (!Array.prototype['forEach']) {
Array.prototype.forEach = function(callback, thisArg) {
if (this == null) { throw new TypeError('Array.prototype.forEach called on null or undefined'); }
var T, k;
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: https://es5.github.com/#x9.11
if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); }
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) { T = thisArg; }
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
你真的不需要理解上面代码的每一行,因为我们感兴趣的是while循环,
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
如果你注意到了,那么这里有一个声明 callback.call(T, KValue, K, O),我们对这里给 call() 方法的参数不感兴趣,但我们真正感兴趣的是 callback 绑定,它是一个 function你给你的forEach javascript 循环。请参阅 call 方法仅调用它所调用的对象(javascript 函数),并使用 this 值和单独提供的参数。
如果您不明白什么是调用,请查看Function.prototype.Call() - JavaScript | MDN。
如果在任何时候你的函数callback 在这种情况下返回,请考虑这一点,循环将照常更新。循环不关心callback 函数是否执行了给它的每一个步骤,如果控制返回到循环,则循环必须完成它的工作。每次循环更新时,callback 都会使用一组新值调用,如您所见,T, KValue, K, O 每次循环更新时都会发生变化,因此,如果您在任何时候从函数返回,即 callback,您就是只需将控制权交给被调用的循环即可.
这就是您在 forEach 循环内跳过迭代的方式。