不久前我就被介绍给了lodash,而我正在接受一个简单的挑战.我正在使用_.forEach()循环在typescript中对Array的对象执行一个函数.但我需要知道它何时到达最后一次迭代才能执行特定的功能.
_.forEach(this.collectionArray, function(value: CreateCollectionMapDto) {
// do some stuff
// check if loop is on its last iteration, do something.
});
Run Code Online (Sandbox Code Playgroud)
我检查了这个或任何与之相关的文档,index但找不到任何东西.请帮我.
Adr*_*tti 14
嘿,也许你可以试试:
const arr = ['a', 'b', 'c', 'd'];
arr.forEach((element, index, array) => {
if (index === (array.length -1)) {
// This is the last one.
console.log(element);
}
});Run Code Online (Sandbox Code Playgroud)
你应该尽可能多地使用本机函数,并在更复杂的情况下使用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);
}
});
Run Code Online (Sandbox Code Playgroud)
forEach回调函数的第二个参数是当前值的索引。
let list = [1, 2, 3, 4, 5];
list.forEach((value, index) => {
if (index == list.length - 1) {
console.log(value);
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7374 次 |
| 最近记录: |