catch forEach最后一次迭代

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)

  • 呵呵...之前的版本更加简洁易读。这个对象的东西是一团糟。 (4认同)
  • 使用“Object.is”来处理像比较两个整数(甚至不能是 -0 或 NaN)这样简单的事情绝对是混乱的。告诉我,@SterlingBourne,有什么好处? (4认同)
  • @SterlingBourne 你能进一步解释一下这些好处是什么吗?(最好也将其包含在答案中) (3认同)
  • 如果你不理解它,那只会是一团糟,Giorgio79。与 == 或 === 相比,使用 Object.is() 作为主要比较方法有很多好处。不过还是谢谢你的评论! (2认同)
  • @SterlingBourne - 有两个问题:1.为什么在只能进行身份比较的地方需要函数调用?(函数调用成本更高)2.如果您期望一个数字,那么应用程序中是否存在一些问题(例如)并得到 NaN,你不应该在调用 Object.is 之前捕获它吗? (2认同)

小智 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)

看起来更积极