Jam*_*son 73 javascript jquery
arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});
Run Code Online (Sandbox Code Playgroud)
循环结束时如何捕获?我可以做,if(i == 3)但我可能不知道我的数组是多少.
jdp*_*nix 133
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 );
}
});
Run Code Online (Sandbox Code Playgroud)
输出:
Last callback call at index 2 with value 3
Run Code Online (Sandbox Code Playgroud)
这种方式的工作方式是测试arr.length数组的当前索引,并传递给回调函数.
Ste*_*rne 18
2018年的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}` );
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我更喜欢这种方式:
arr.forEach(function(i, idx, array){
if (idx + 1 === array.length){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
Run Code Online (Sandbox Code Playgroud)
看起来更积极
| 归档时间: |
|
| 查看次数: |
70989 次 |
| 最近记录: |