简体   繁体   中英

Does a `for of` loop re-evaluate a filtered array?

Consider this piece of javascript code:

cont groups = [{ name: 'Sean', type: 'A' }, 
      { name: 'Jen', type: 'A' }, 
      { name: 'Tom', type: 'B'}]

for(const group of groups.filter(g => g.type === 'A')) {
    ...do some work
}

Would the for loop re-evaluate the groups filter each iteration? How would one go about testing that? In this example it does not matter much, however, on large collections it may be important to instead lift the filter operation out into its own variable.

No it does not reevaluate on each iteration.It does it at the starting. For...of loop works with iterator object which counts all the elements index internally. For each iteration it calls the next() method of iterator to get next element. For more information about iterators please refer to this link

Based on Pointy's suggestion in his comment, I dropped the console.log into the filter callback. In the example below, I took it a step further and used some count variable to make sure its not re-evaluating the filter function in side each iteration. If it was, I would have expected to a value of 6 (3 items in array times 2 matched elements)

 const groups = [{ name: 'Sean', type: 'A' }, { name: 'Jen', type: 'A' }, { name: 'Tom', type: 'B'}] let cnt = 0 for(const group of groups.filter(g => { console.log("I am here") cnt += 1 return g.type === 'A' })) { document.getElementById("count1").value = cnt } cnt = 0 const filteredGroup = groups.filter(g => { console.log("I am here") cnt += 1 return g.type === 'A' }) for(const group of filteredGroup) { document.getElementById("count2").value = cnt } 
 <div> <label>Filter inline with for loop</label> <input type="text" id="count1" /> <br /> <br /> <label>Filter set outside of loop</label> <input type="text" id="count2" /> <br /> </div> 

This appears to confirm some of the comments and RK_15's answer which is that it does not reevaluate the filter inside of a for loop.

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