0

I was just playing around with for...of and tried to see how intuitive it was to get both the key and value of an entity being looped on and got to the following state:

for (var divEntries of Array.from(document.querySelectorAll('div')).entries()) {
    console.log(divEntries[0]); // Key
    console.log(divEntries[1]); // Value
}

Is there a better way to do this which would be a bit more semantic than using array positions on entries?

3
  • 1
    The entries of querySelectorall are iterable anyway. You don't need that Array.from Commented Jun 14, 2016 at 19:51
  • 1
    @BenjaminGruenbaum: Not in all browsers that already support for of :-/ Commented Jun 14, 2016 at 20:00
  • The question is about for...of though Commented Jun 15, 2016 at 10:27

2 Answers 2

3

A clearer way would be by using Destructuring assignment

for (let [key, value] of Array.from(document.querySelectorAll('div')).entries() ) {
   console.log(key);
   console.log(value);
} 

MDN has a list of examples about how for...of can be used including the example with destructing.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, it is more idiomatic to use destructuring in the loop header:

for (let [index, value] of Array.from(document.querySelectorAll('div')).entries()) {
    console.log(index); // Key
    console.log(value); // Value
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.