最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - map.delete(key) during map.forEach - Stack Overflow

programmeradmin1浏览0评论

Typically, you cannot safely delete items from an list while you're looping through that list. Does this concept remain true for ES6 Maps?

I tried this simple test without exceptions:

var map = new Map([['a',1],['b',2],['c',3]]);
    map.forEach((value,key,map)=>
    {
          map.delete(key);
          let str = `["${key}",${value}] was deleted. `;
          str += `map.size = ${map.size}`;
          console.log(str);
    });

Typically, you cannot safely delete items from an list while you're looping through that list. Does this concept remain true for ES6 Maps?

I tried this simple test without exceptions:

var map = new Map([['a',1],['b',2],['c',3]]);
    map.forEach((value,key,map)=>
    {
          map.delete(key);
          let str = `["${key}",${value}] was deleted. `;
          str += `map.size = ${map.size}`;
          console.log(str);
    });

It seems ok.

Update: I just read this reference from Mozilla. It is certainly doable. I'd be interested in any performance benchmarks comparing this method of deletion with other methods (on larger datasets).

Share Improve this question edited Aug 11, 2020 at 12:33 Lonnie Best asked Sep 11, 2017 at 5:52 Lonnie BestLonnie Best 11.4k14 gold badges66 silver badges109 bronze badges 1
  • 3 You can, it's safe, see stackoverflow.com/questions/35940216/… – petronius Commented Oct 25, 2018 at 9:19
Add a comment  | 

2 Answers 2

Reset to default 6

Well I guess you're right. I am not quite familiar with the ES6 Maps, but had done a bit of research and found this blog a bit helpful where it explains about the MAPS:

https://hackernoon.com/what-you-should-know-about-es6-maps-dc66af6b9a1e

Here you will get the deleting mechanism explanation too:
Something like this:

var m = new Map()
m.set('a', 1)
m.set('b', 2)
m.delete('a'); // true
m.delete('c'); // false (key was not there to delete)

Hope this helps.

Why? If you are working with the same instance, actually you can delete. It has functions which are used for deleting an item, so you can delete.

But from the side of Optimization don't delete any item from the Map or array. Javascript engines have optimizations based on the shape of the object. If it is the same over some reference to that object, it would be optimized. Instead of this, create a new object from the filtered values of the current object.

var map =  new Map([['a',1],['b',2],['c',3]]);
map.forEach((value,key,map)=>
{
      map.delete(key);
});

console.log(map);

There are some languages ( C# ), that you can't remove items from the IEnumerable in the for each loop, because it works another way under the hood, actually it gives you only read and update access, not delete.

发布评论

评论列表(0)

  1. 暂无评论