Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - cursor.forEach()中的“continue”(“continue” in cursor.forEach())

I'm building an app using meteor.js and MongoDB and I have a question about cursor.forEach().

(我正在使用meteor.js和MongoDB构建一个应用程序,我有一个关于cursor.forEach()的问题。)

I want to check some conditions in the beginning of each forEach iteration and then skip the element if I don't have to do the operation on it so I can save some time.

(我想检查每个forEach迭代开始时的一些条件,然后跳过元素,如果我不必对它进行操作,那么我可以节省一些时间。)

Here is my code:

(这是我的代码:)

// 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();
  }
});

I know I could turn cursor to array using cursor.find().fetch() and then use regular for-loop to iterate over elements and use continue and break normally but I'm interested if there is something similiar to use in forEach().

(我知道我可以使用cursor.find()。fetch()将光标转换为数组,然后使用常规for循环迭代元素并使用continue并正常打破但是我很感兴趣,如果在forEach中有类似的东西( )。)

  ask by Drag0 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Each iteration of the forEach() will call the function that you have supplied.

(forEach()每次迭代都将调用您提供的函数。)

To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

(要在任何给定的迭代中停止进一步处理(并继续下一个项目),您只需在适当的位置从函数return :)

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

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...