gpt4 book ai didi

javascript - ES6 中需要 Map 类吗?

转载 作者:行者123 更新时间:2023-11-28 15:05:54 25 4
gpt4 key购买 nike

ES6 标准的新功能之一是 Map 类,用于创建键:值数据集合。好吧,对。但是,为什么 Javascript 需要这样一个类呢? JS 对象表示法实际上也是一个 key:value 数据集合,这还不够吗?那么,有什么区别呢?

最佳答案

来自MDN :

Objects and maps compared

Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better:

  • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.
  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods. If you're still not sure which one to use, ask yourself the following questions:

  • Are keys usually unknown until run time, do you need to look them up dynamically?
  • Do all values have the same type, and can be used interchangeably?
  • Do you need keys that aren't strings?
  • Are key-value pairs often added or removed?
  • Do you have an arbitrary (easily changing) amount of key-value pairs?
  • Is the collection iterated?

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

对我个人而言,最重要的是支持任何类型的值作为键,而不仅仅是字符串。

关于javascript - ES6 中需要 Map 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38954672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com