catch forEach last iteration

arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

149902 次浏览

ES6 + 的最新答案是 给你


arr = [1, 2, 3];


arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});

产出:

Last callback call at index 2 with value 3

其工作方式是根据传递给 回调函数回调函数的数组的当前索引测试 arr.length

2021年 ES6 + 的答案是:

    const arr = [1, 2, 3];


arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
const arr= [1, 2, 3]
arr.forEach(function(element){
if(arr[arr.length-1] === element){
console.log("Last Element")
}
})

我更喜欢这样:

arr.forEach(function(i, idx, array){
if (idx + 1 === array.length){
console.log("Last callback call at index " + idx + " with value " + i );
}
});

看起来更积极