问题描述
的每次迭代都forEach()
将调用您提供的函数。要在任何给定的迭代中停止进一步处理(并继续下一项),您只需return
在适当的点从函数中执行:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
解决方法
我正在使用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( )。