【问题标题】:How to get the last iteration in a _.forEach() loop如何在 _.forEach() 循环中获取最后一次迭代
【发布时间】:2017-11-21 15:51:57
【问题描述】:

不久前我被介绍给 lodash,我遇到了一个似乎很简单的挑战。 我正在使用_.forEach() 循环对打字稿中的数组对象执行函数。但我需要知道它何时到达最后一次迭代以执行特定功能。

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

我检查了这个文档或任何与 index 相关的文档,但找不到任何东西。请帮帮我。

【问题讨论】:

    标签: typescript lodash


    【解决方案1】:

    嘿,也许你可以试试:

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

    【讨论】:

    • 我看到了这个,但我想要 lodash。我想我将不得不接受这个。谢谢。
    • 我已经更新了我的消息以添加一个带有 lodash 的示例
    【解决方案2】:

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

    let list = [1, 2, 3, 4, 5];
    
    list.forEach((value, index) => {
      if (index == list.length - 1) {
        console.log(value);
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 2019-02-02
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2023-01-01
      • 2019-04-24
      相关资源
      最近更新 更多