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()
。
ベストアンサー1
の各反復でforEach()
は、指定した関数が呼び出されます。特定の反復内でそれ以上の処理を停止し、次の項目に進むには、return
適切な時点で関数を終了するだけです。
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});