ES6 introduced new data structures to take care of some problems that the language did not take care of.
ES6引入了新的数据结构,以解决该语言无法解决的一些问题。
Before its’ introduction, people generally used Objects to do the work.
在引入之前,人们通常使用对象来完成这项工作。
However, Objects do not allow keys to be anything other than a string or integer. Keys in a Map, on the other hand, can be anything (object, array, string, or number). This allows for some interesting uses.
但是,对象不允许键只能是字符串或整数。 另一方面,Map中的键可以是任何东西(对象,数组,字符串或数字)。 这允许一些有趣的用途。
Features that objects do not have
对象没有的功能
- Can store Arrays and Objects as keys. 可以将数组和对象存储为键。
- Easily iterable in order of entry. 易于按输入顺序进行迭代。
如何建立地图 (How to Create a Map)
let m = new Map()
内置方法 (Built in Methods)
.set()
。组()
Use the set method to add entries to a Map.
使用set方法将条目添加到Map。
m.set('key', 'value')
m.set('hello', 'world)
.get()
。得到()
Use the get method to get the value of a Key, Value pair in a map
使用get方法获取映射中的键,值对的值
m.get('hello')
// 'world'
.has()
。有()
Use the has method to check if a key is in the Map. Returns a boolean.
使用has方法检查键是否在Map中。 返回一个布尔值。
m.has('hi')
//falsem.has('hello')
//true
.size()
。尺寸()
Use the size method to check the size of a Map. Something that is not available with an object.
使用size方法检查地图的大小。 某些物件无法使用的物件。
m.size()
//true
.delete()
。删除()
Use the delete method to remove an entry from a Map.
使用delete方法从地图中删除条目。
m.delete('hello')
// will remove hello from the Mapm.size()
// 1
遍历地图 (Iterating Through a Map)
One of the biggest improvements of a Map over an Object is the ability to iterate through the data structure in the order that the objects were added.
Map over Object的最大改进之一是能够按添加对象的顺序遍历数据结构。
In doing this we also have access to the value using destructuring. We can use a “for, of” loop to get this done.
在此过程中,我们还可以使用解构来访问值。 我们可以使用“ for,of”循环来完成此任务。
for(const [k, v] of m){ console.log(k, v)}// hello world
结论 (Conclusion)
These features allow for a more expansive set of use cases and better ways to solve problems.
这些功能允许使用范围更广的用例集,以及解决问题的更好方法。
Thank you for reading! Please follow me on Twitter @thedrewprint and connect with me on LinkedIn. — Andrew Richards
感谢您的阅读! 请在Twitter @thedrewprint上关注我,并在LinkedIn上与我联系。 -安德鲁·理查兹(Andrew Richards)
翻译自: https://medium.com/@arichards4814/maps-in-javascript-33508a5cb6e7