javascript - JavaScript 中的映射与对象

标签 javascript dictionary ecmascript-6

我刚刚发现 this feature :

Map: Map objects are simple key/value maps.

这让我很困惑。常规 JavaScript 对象是字典,所以 Map与字典不同?从概念上讲,它们是相同的(根据 another question on Stack Overflow)

文档也无济于事:

Map objects are collections of key/value pairs where both the keys and values may be arbitrary ECMAScript language values. A distinct key value may only occur in one key/value pair within the Map’s collection. Distinct key values as discriminated using the a comparision algorithm that is selected when the Map is created.

A Map object can iterate its elements in insertion order. Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Map objects specification is only intended to describe the required observable semantics of Map objects. It is not intended to be a viable implementation model.

……对我来说仍然听起来像是一个对象,所以很明显我错过了一些东西。

为什么 JavaScript 获得了(良好支持的)Map目的?它有什么作用?

最佳答案

根据 MDN:

A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.

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, 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. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, 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.

Map

顺序迭代是开发人员长期以来一直想要的功能,部分原因是它可以确保在所有浏览器中都具有相同的性能。所以对我来说这是一件大事。

myMap.has(key)方法会特别方便,myMap.size属性。

关于javascript - JavaScript 中的映射与对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18541940/

相关文章:

javascript - 如何在 V8 中将对象传递给 JavaScript 回调

javascript - Promise.all 和使用加号添加 promise 有什么区别?

javascript - 使用 array.map() 映射到另一个类

javascript - React 应用导入重复

javascript - 内部和外部带括号的闭包之间的区别

javascript - 清理比较

python - 使用宽松字典映射列中的值

python - python 对象的可读名称作为字典键

c# - 将 json 字符串反序列化为对象 - Silverlight

javascript - 加载事件在脚本加载之前触发服务器端脚本