jquery catch forEach last iteration

ogsagwnx  于 2023-04-05  发布在  jQuery
关注(0)|答案(4)|浏览(104)
arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

如何在循环结束时捕获?我可以使用if(i == 3),但我可能不知道数组的编号。

dfuffjeb

dfuffjeb1#

参见updated answer for ES6+

arr = [1, 2, 3]; 

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

将输出:

Last callback call at index 2 with value 3

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

41ik7eoe

41ik7eoe2#

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

mbyulnm03#

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})
wnavrhmk

wnavrhmk4#

我更喜欢这样:

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

看起来更积极

相关问题