如何在_.forEach()循环中获取最后一次迭代

时间:2017-11-21 15:51:58

标签: typescript lodash

我很久以前就被介绍给了lodash,而我正在接受一个简单的挑战。 我正在使用_.forEach()循环在typescript中对Array的对象执行函数。但我需要知道它何时到达最后一次迭代才能执行特定的功能。

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

我检查了文档中的这个或与index有关但找不到任何内容。请帮帮我。

2 个答案:

答案 0 :(得分:9)

嘿,也许你可以试试:

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

你应该尽可能多地使用本机函数,并在更复杂的情况下使用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);
    }
});

答案 1 :(得分:3)

forEach回调函数的第二个参数是当前值的索引。

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

list.forEach((value, index) => {
  if (index == list.length - 1) {
    console.log(value);
  }
})