簡體   English   中英

在 ES6 javascript 中檢測 FOR OF 循環中的最后一次迭代

[英]Detect last iteration in FOR OF loop in ES6 javascript

有多種方法可以找出forfor...in循環的最后一次迭代。 但是我如何在for...of循環中找到最后一次迭代。 我在文檔中找不到。

for (item of array) {
    if (detect_last_iteration_here) {
        do_not_do_something
    }
}

一種可能的方法是在循環外初始化一個計數器,並在每次迭代時遞減它:

 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); }
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}

請注意, !--iterations被評估為!(--iterations)並且當iterations=1時表達式將為true

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

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

另一種方法是像 Shidersz 建議的那樣將計數保持在循環之外。 我不認為你想檢查indexOf(item)因為如果最后一個項目在數組中的其他地方重復,這會帶來問題......

您可以對數組進行切片並省略最后一個元素。

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

如果您想根據特定索引更改循環行為,那么在 for 循環中使用顯式索引可能是個好主意。

如果您只是想跳過最后一個元素,您可以執行以下操作

for (item of array.slice(0, -1)) {
    //do something for every element except last
}

找到最后一個循環的最簡單方法,比方說,在迭代過程中去掉最后一個逗號插入,是將數組的長度與其最后一項的索引進行比較。

const arr = ["verb", "noun", "pronoun"];

for (let item of arr) {
    if (arr.length -1 !== arr.indexOf(item)) {
        console.log('With Commas');
    } else {
        console.log('No Commars');
    }
}

似乎沒有任何關於 for..of 的規范。 似乎有兩種解決方法:

如果可以,只需將一個標記推到數組的末尾並對該標記進行操作,如下所示:

myArray.push('FIN')
for (el of myArray){
    if (el === 'FIN')
        //ending code
}

或者,您可以使用以下內容來獲取可以與 Array.length 一起使用的索引

在此處輸入鏈接描述

pre> 
const chain = ['ABC', 'BCA', 'CBA'];
let findOut;
for (const lastIter of chain) {
    findOut = lastIter;       //Last iteration value stored in each iteration. 
} 

控制台日志(查找);

enter code here
CBA

一個更通用的替代方案,牢固地基於組合原則,是使用生成器函數實現另一個迭代器。 事實上,這將組合這兩個迭代器。

新的迭代器基本上會將值的實際產生委托給原始迭代器。 不同的是,前者會比后者“領先一步”。 通過這樣做,新的迭代器將能夠為每個元素驗證迭代是否在下一個元素時停止。

function* withLast(iterable) {
  const iterator = iterable[Symbol.iterator]();
  let curr = iterator.next();
  let next = iterator.next();
  while (!curr.done) {
    yield [next.done, curr.value];
    [curr, next] = [next, iterator.next()];
  }
}

請注意,在第一次迭代中, next被調用了兩次。 對於next每次迭代, next總是被調用一次,僅針對當前迭代前一步對應的元素。

了解有關JavaScript 迭代協議的更多信息,以了解有關該實現的更多信息。

一個更具體的例子:

 function* withLast(iterable) { const iterator = iterable[Symbol.iterator](); let curr = iterator.next(); let next = iterator.next(); while (!curr.done) { yield [next.done, curr.value]; [curr, next] = [next, iterator.next()]; } } const arr = [1, 2, 3]; for (const [isLast, element] of withLast(arr)) { console.log(`${element} ${isLast ? 'is' : 'is not'} the last.`); }

由於像索引或迭代器的實際長度這樣的概念——后者在某些極端情況下甚至不是無限迭代器——在這個解決方案中沒有使用,這種方法非常適合任何類型的迭代器。

另一個例子:

 function* withLast(iterable) { const iterator = iterable[Symbol.iterator](); let curr = iterator.next(); let next = iterator.next(); while (!curr.done) { yield [next.done, curr.value]; [curr, next] = [next, iterator.next()]; } } // Generator function that creates a "generic" iterator: function* gen() { yield 'a'; yield 'b'; yield 'c'; } for (const [isLast, element] of withLast(gen())) { console.log(`${element} ${isLast ? 'is' : 'is not'} the last.`); }

使用 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM