简体   繁体   中英

How would I know when I'm iterating over the last object in a DOM collection with for…of in JavaScript?

I'm using the following code to iterate through a collection of DOM elements (as seen here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Iterating_over_a_DOM_collection )

let articleParagraphs = document.querySelectorAll("article > p");

for (let paragraph of articleParagraphs) {
  paragraph.classList.add("read");
}

How would I detect which object in the collection I'm currently looping through? And most importantly, how would I know when I'm currently looking at the last object?

Set a variable to the last paragraph in the list.

var lastParagraph = articleParagraphs[articleParagraphs.length-1];
for (let paragraph of articleParagraphs) {
    paragraph.classList.add("read");
    if (paragraph == lastParagraph) {
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM