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

标签 typescript lodash

不久前我接触了 lodash,现在我遇到了一个看似简单的挑战。 我正在使用 _.forEach() 循环对 typescript 中的数组对象执行函数。但我需要知道执行特定功能的最后一次迭代是什么时候。

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

我检查了有关此内容或任何与 index 有关的文档,但找不到任何内容。请帮助我。

最佳答案

嘿,也许你可以试试:

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

关于typescript - 如何在 _.forEach() 循环中获取最后一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417194/

相关文章:

javascript - 在 angular-archwizard 步骤上更改边框颜色

javascript - 数组中的展开操作出错。 TS1005 : ',' expected. typescript

Angular 项目中的 Lodash 漏洞

Javascript:直接用索引替换 Array.splice()

javascript - 嵌套模块的 Angular 404 页面路由

javascript - Typescript 根据字段将对象映射到带有新对象的数组

javascript - 根据另一个对象数组过滤对象数组

javascript - 将参数绑定(bind)到传递给 lodash 的 "debounce"的输入函数

javascript - 如何按对象数组中的任何属性过滤数据?

typescript - 为什么类型 `Record<string,unknown>` 不接受具有定义键的对象作为值