不久前我接触了 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/