简体   繁体   English

ES2015-集,图和数组问题

[英]ES2015 - Sets, Maps and Array Questions

I'm just looking into ES2015, and coming up to Maps, Sets and Arrays. 我正在研究ES2015,并介绍了Maps,Sets和Arrays。

Question 1 问题1

Firstly I'm interested in why they all use a different method to add items to it. 首先,我对为什么他们都使用不同的方法向其中添加项目感兴趣。

  • Set.add("item");
  • Map.set("item");
  • Array.push("item");

is there method to the madness rather than keeping them all as .push ? 有什么办法可以使他们发疯,而不是把它们都保留为.push吗?

Question 2 问题2

size vs length. 大小与长度。

Why have Map and Set got .size but Array has .length why not use the same? 为什么Map和Set的.size但Array的.length为什么不使用相同的.length

Question 3 问题3

When would you use Map over Array? 什么时候使用“基于数组的映射”? can anybody give a real world example for this, I understand you can do things like use objects as keys in Maps, but why would you do that in the first place. 任何人都可以为此举一个真实的例子,我知道您可以做一些事情,例如在Maps中使用对象作为键,但是为什么首先要这么做。


Hopefully somebody can clear this up to help inform other new starters to ES2015, thanks. 希望有人可以解决此问题,以帮助其他新手了解ES2015。

Sets, Maps and Arrays use different methods, because these methods do different things. 集,地图和数组使用不同的方法,因为这些方法执行不同的操作。 Array.prototype.push() adds one or more elements to the end of the array. Array.prototype.push()将一个或多个元素添加到数组的末尾。 Set.prototype.add() works similarly, but it only accepts one argument. Set.prototype.add()工作原理类似,但只接受一个参数。 If it was named push() , some people would think that it works the same as the array method, and they'd try doing set.push(1, 2, 3) and they'd be confused why it adds only the first element. 如果将其命名为push() ,则有些人会认为它的作用与array方法相同,因此他们会尝试执行set.push(1, 2, 3) ,并且会感到困惑,为什么只添加第一个元件。

Map.prototype.set() is a completely different thing. Map.prototype.set()是完全不同的东西。 From MDN : MDN

The set() method adds or updates an element with a specified key and value to a Map object. set()方法将具有指定键和值的元素添加或更新到Map对象。

If an element with a specified key already exists, this method doesn't add any element to the Map, but only updates the value of that element. 如果具有指定键的元素已经存在,则此方法不会将任何元素添加到Map中,而只会更新该元素的值。

You second question was answered on this blog : 在此博客上回答了第二个问题:

length is for sequences, data structures that are indexable – like arrays. length用于序列,可索引的数据结构(如数组)。 size is for collections that are primarily unordered – like maps and sets. size适用于基本上无序的集合-如地图和集合。

I don't really understand your third question. 我真的不明白你的第三个问题。 Maps and Arrays are completely different data structures. 映射和数组是完全不同的数据结构。 Maps are similar to objects, see Maps vs Objects in ES6, When to use? 地图类似于对象,请参阅ES6中的“地图与对象”,何时使用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM