2017-11-21 12 views
0

私はlodashをあまり前に導入していませんでした。 _.forEach()ループを使用して、typescript内の配列のオブジェクトに関数を実行しています。しかし、私は特定の機能を実行するために最後の反復になるときを知る必要があります。_.forEach()ループの最後の反復を取得する方法

_.forEach(this.collectionArray, function(value: CreateCollectionMapDto) { 
     // do some stuff 
     // check if loop is on its last iteration, do something. 
    }); 

私はindexを行うには、このためのマニュアルまたは何かをチェックするが、何かを見つけることができませんでした。私を助けてください。

答えて

3

ねえ、多分あなたは試みることができる:

const arr = ['a', 'b', 'c', 'd']; 
 
arr.forEach((element, index, array) => { 
 
    if (index === (array.length -1)) { 
 
     // This is the last one. 
 
     console.log(element); 
 
    } 
 
});

あなたはより多くのCOMPLEXE例は

を来たときに可能とlodash限り多くのネイティブ関数を使用しますが、とすべきですあなたもできる:lodash

const _ = require('lodash'); 

const arr = ['a', 'b', 'c']; 
_.forEach(arr, (element, index, array) => { 
    if (index === (array.length -1)) { 
     // last one 
     console.log(element); 
    } 
}); 
+0

私はこれを見ましたが、私はロダシが欲しかったです。私はこれを解決しなければならないと思う。ありがとう。 –

+0

メッセージを更新して、lodashで例を追加しました –

1

forEachコールバック関数の2番目のパラメータは、現在の値のインデックスです。

let list = [1, 2, 3, 4, 5]; 

list.forEach((value, index) => { 
    if (index == list.length - 1) { 
    console.log(value); 
    } 
}) 
関連する問題