gpt4 book ai didi

javascript - JavaScript 中的映射与对象

转载 作者:IT老高 更新时间:2023-10-28 13:13:22 25 4
gpt4 key购买 nike

我刚刚发现 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 isstored at a key. Because of this, Objects have been used as Mapshistorically; however, there are important differences between Objectsand 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). Thekeys 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 keeptrack of size for an Object.

Map

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

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

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

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