在 ES6 javascript 中检测 FOR OF 循环中的最后一次迭代

Vla*_*col 20 javascript iterator loops for-loop ecmascript-6

有多种方法可以找出 a forandfor...in循环的最后一次迭代。但是我如何找到循环中的最后一次迭代for...of。我在文档中找不到。

for (item of array) {
    if (detect_last_iteration_here) {
        do_not_do_something
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 23

一种方法是使用Array.prototype.entries()

for (const [i, value] of arr.entries()) {
    if (i === arr.length - 1) {
        // do your thing
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是像 Shidersz 建议的那样将计数保持在循环之外。我认为您不想检查,indexOf(item)因为如果最后一项在数组中的其他位置重复,则会出现问题...


Shi*_*rsz 22

一种可能的方法是在循环外初始化一个计数器,并在每次迭代时递减它:

const data = [1, 2, 3];
let iterations = data.length;

for (item of data)
{
    if (!--iterations)
        console.log(item + " => This is the last iteration...");
    else
        console.log(item);
}
Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Run Code Online (Sandbox Code Playgroud)

请注意,!--iterations被评估为!(--iterations)并且表达式将是truewhen iterations=1


Nin*_*olz 8

您可以对数组进行切片并省略最后一个元素。

var array = [1, 2, 3],
    item;
    
for (item of array.slice(0, -1)) {
    console.log(item)
}
Run Code Online (Sandbox Code Playgroud)

  • OP想要检测最后一个元素,而不是从数组中删除最后一个元素 (4认同)

Aks*_*kar 5

使用ES6,通过调用数组上的entries()方法,你可以做到这一点=>

const array = [1, 2, 3];
for (const [i, v] of array.entries()) {
    //Handled last iteration
    if( i === array.length-1) {
        continue;
    }
    console.log(i, v)// it will print index and value
}
Run Code Online (Sandbox Code Playgroud)