363

我正在使用meteor.js 和MongoDB 构建一个应用程序,我有一个关于cursor.forEach() 的问题。我想在每次 forEach 迭代开始时检查一些条件,然后如果我不需要对其进行操作则跳过该元素,这样我可以节省一些时间。

这是我的代码:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection.forEach(function(element){
  if (element.shouldBeProcessed == false){
    // Here I would like to continue to the next element if this one 
    // doesn't have to be processed
  }else{
    // This part should be avoided if not neccessary
    doSomeLengthyOperation();
  }
});

我知道我可以使用 cursor.find().fetch() 将光标转换为数组,然后使用常规 for 循环遍历元素并正常使用 continue 和 break 但我很感兴趣是否在 forEach( )。

4

7 回答 7

692

的每次迭代都forEach()将调用您提供的函数。要在任何给定的迭代中停止进一步处理(并继续下一项),您只需return在适当的点从函数开始:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});
于 2013-08-26T21:08:32.577 回答
16

在我看来,最好的方法是使用该filter 方法forEach来实现这一点,因为在块中返回是没有意义的;有关您的代码段的示例:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

这将缩小您的范围elementsCollection并仅保留filtred应处理的元素。

于 2017-07-12T02:15:47.407 回答
11

这是使用for ofandcontinue代替的解决方案forEach


let elementsCollection = SomeElements.find();

for (let el of elementsCollection) {

    // continue will exit out of the current 
    // iteration and continue on to the next
    if (!el.shouldBeProcessed){
        continue;
    }

    doSomeLengthyOperation();

});

如果您需要在循环中使用异步函数,而这些函数在forEach. 例如:


(async fuction(){

for (let el of elementsCollection) {

    if (!el.shouldBeProcessed){
        continue;
    }

    let res;

    try {
        res = await doSomeLengthyAsyncOperation();
    } catch (err) {
        return Promise.reject(err)
    }

});

})()
于 2019-08-22T20:24:13.327 回答
4

利用 JavaScript的短路评估。如果el.shouldBeProcessed返回真,doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);
于 2019-08-28T21:30:44.210 回答
3

简单的答案是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 版 forforEach循环中指定的实现。

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绑定,它是functionforEach在 javascript 中为循环提供的。请参阅该call方法仅调用它所调用的对象(javascript 函数),并使用this单独提供的值和参数。

如果您不了解什么是调用,请查看Function.prototype.Call() - JavaScript | MDN

如果在任何时候你的函数callback在这种情况下返回任何时候循环都会像往常一样更新,请考虑这一点。循环不关心callback函数是否执行了给它的每一个步骤,如果控制已经返回到循环,循环必须完成它的工作。每次循环更新时,callback都会使用一组新值调用,正如您所看到的,T, KValue, K, O每次循环更新时都会发生变化,所以如果您在任何时候从函数返回,即callback无论您在什么时候从函数返回,您都只是将控制权交给您被调用的循环,如果您想在给定条件下跳过函数内部的一些操作,那么只需将 return 语句放在您想要的那些语句之前跳过。

这就是您在循环内跳过迭代的方式forEach

于 2021-05-01T12:59:29.300 回答
0

如果您使用的是经典for循环并且不想使用continue,您可以在其中使用自执行函数并使用它return来模仿continue行为:

for (let i = 0; i < 10; i++) {
    (() => {
        if (i > 5) return;
        console.log("no.", i)
    })();
}

console.log("exited for loop")

输出:

[LOG]: "no.",  0 
[LOG]: "no.",  1 
[LOG]: "no.",  2 
[LOG]: "no.",  3 
[LOG]: "no.",  4 
[LOG]: "no.",  5 
[LOG]: "exited for loop" 
于 2021-07-27T16:00:58.633 回答
-4

使用continue语句而不是 return 来跳过 JS 循环中的迭代。

于 2020-09-25T11:58:33.753 回答