用JavaScript映射

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值