ES6: Is it dangerous to delete elements from Set/Map during Set/Map iteration?

后端 未结 2 847
情话喂你
情话喂你 2020-11-28 13:05

Safe code for new Set() may look like:

let items = [];
for (let item of set)
  if (isBad(item))
    items.push(item);
for (let item of items)
  s         


        
2条回答
  •  孤街浪徒
    2020-11-28 14:00

    I would say yes, it's safe. When you iterate over the Set/Map using for ... of under the hood the loop is going through @@iterator. And Iterator operates with .next() only: so no indices and no matter what is before the current position. Only one next element is important.

    So until you remove elements "in front of" the current iterator position - it's safe to do it.

提交回复
热议问题