Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

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

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)
  set.delete(item)

Can I simplify code to:

for (let item of set)
  if (isBad(item))
    set.delete(item);

Safe code for new Map() may look like:

let keys = [];
for (let [key, val] of map)
  if (isBadKey(key) || isBadValue(val))
    keys.push(key);
for (let key of keys)
  map.delete(key)

Can I simplify code to:

for (let [key, val] of map)
  if (isBadKey(key) || isBadValue(val))
    map.delete(key)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can simplify to that, it's totally safe.

  • Sets and Maps are always iterated in insertion order
  • Deleting an item does not affect the position of any iterator - you can visualise the shape of the collection not being changed, just being emptied.
  • So: elements that are deleted and have not yet been iterated won't be iterated
  • Elements that have already been iterated and are deleted (like in your case) won't affect anything but other iterations/lookups.
  • Elements that are added (and are not already part of the collection) during the iteration will always be iterated

From that last point follows that the only dangerous thing to do would be something like

const s = new Set([1]);
for (let x of s) {
    s.delete(x);
    s.add(1);
}

but not because of undefined behaviour or memory accumulation, but because of the infinite loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...