了解JavaScript中的Map和Set对象

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。

In JavaScript, developers often spend a lot of time deciding the correct data structure to use. This is because choosing the correct data structure can make it easier to manipulate that data later on, saving time and making code easier to comprehend. The two predominant data structures for storing collections of data are Objects and Arrays (a type of object). Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.

在JavaScript中,开发人员通常会花费大量时间来决定要使用的正确数据结构。 这是因为选择正确的数据结构可以使以后更轻松地操作该数据,节省时间并使代码更易于理解。 用于存储数据集合的两个主要数据结构是对象数组 (对象的一种)。 开发人员使用对象存储键/值对,使用数组存储索引列表。 但是,为了给开发人员更大的灵活性,ECMAScript 2015规范引入了两种新的可迭代对象类型: Maps是键/值对的有序集合, Sets是唯一值的集合。

In this article, you will go over the Map and Set objects, what makes them similar or different to Objects and Arrays, the properties and methods available to them, and examples of some practical uses.

在本文中,您将介绍Map和Set对象,使它们与Objects和Arrays相似或不同,使它们可用的属性和方法以及一些实际用途的示例的原因。

地图 (Maps)

A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries. Maps have elements of both Objects (a unique key/value pair collection) and Arrays (an ordered collection), but are more similar to Objects conceptually. This is because, although the size and order of entries is preserved like an Array, the entries themselves are key/value pairs like Objects.

映射是键/值对的集合,可以将任何数据类型用作键并可以维护其条目的顺序。 映射具有对象(唯一键/值对集合)和数组(有序集合)的元素,但从概念上讲与对象更相似。 这是因为,尽管条目的大小和顺序像数组一样保留,但条目本身是键/值对,例如对象。

Maps can be initialized with the new Map() syntax:

可以使用new Map()语法初始化new Map()

const map = new Map()

This gives us an empty Map:

这给了我们一个空的地图:


   
   
Output
Map(0) {}

向地图添加值 (Adding Values to a Map)

You can add values to a map with the set() method. The first argument will be the key, and the second argument will be the value.

您可以使用set()方法将值添加到地图。 第一个参数将是键,第二个参数将是值。

The following adds three key/value pairs to map:

下面将三个键/值对添加到map

map.set('firstName', 'Luke')
map.set('lastName', 'Skywalker')
map.set('occupation', 'Jedi Knight')

Here we begin to see how Maps have elements of both Objects and Arrays. Like an Array, we have a zero-indexed collection, and we can also see how many items are in the Map by default. Maps use the => syntax to signify key/value pairs as key => value:

在这里,我们开始了解Map如何同时具有Object和Array的元素。 像数组一样,我们有一个零索引的集合,并且我们还可以查看默认情况下Map中有多少个项目。 映射使用=>语法将键/值对表示为key => value


   
   
Output
Map(3) 0: {"firstName" => "Luke"} 1: {"lastName" => "Skywalker"} 2: {"occupation" => "Jedi Knight"}

This example looks similar to a regular object with string-based keys, but we can use any data type as a key with Maps.

该示例看起来类似于带有基于字符串的键的常规对象,但是我们可以将任何数据类型用作Maps的键。

In addition to manually setting values on a Map, we can also initialize a Map with values already. We do this using an Array of Arrays containing two elements that are each key/value pairs, which looks like this:

除了在Map上手动设置值外,我们还可以使用已有的值初始化Map。 我们使用包含两个元素的数组数组来完成此操作,每个元素都是键/值对,如下所示:

[ [ 'key1', 'value1'], ['key2', 'value2'] ]

Using the following syntax, we can recreate the same Map:

使用以下语法,我们可以重新创建相同的Map:

const map = new Map([
  ['firstName', 'Luke'],
  ['lastName', 'Skywalker'],
  ['occupation', 'Jedi Knight'],
])

Note: This example uses trailing commas, also referred to as dangling commas. This is a JavaScript formatting practice in which the final item in a series when declaring a collection of data has a comma at the end. Though this formatting choice can be used for cleaner diffs and easier code manipulation, whether to use it or not is a matter of preference. For more information on trailing commas, see this Trailing Comma article from the MDN web docs.

注意:此示例使用结尾逗号 ,也称为悬挂逗号 。 这是一种JavaScript格式化惯例,其中声明数据集合时,系列中的最后一项在末尾带有逗号。 尽管可以将这种格式选择用于更清晰的差异和更轻松的代码操作,但是是否使用它是一个优先事项。 有关尾随逗号的更多信息,请参见MDN Web文档中的尾随逗号文章

Incidentally, this syntax is the same as the result of calling Object.entries() on an Object. This provides a ready-made way to convert an Object to a Map, as shown in the following code block:

顺便说一句,此语法与在对象上调用Object.entries()的结果相同。 这提供了一种将Object转换为Map的现成方法,如以下代码块所示:

const luke = {
  firstName: 'Luke',
  lastName: 'Skywalker',
  occupation: 'Jedi Knight',
}

const map = new Map(Object.entries(luke))

Alternatively, you can turn a Map back into an Object or an Array with a single line of code.

或者,您可以使用单行代码将Map转换回Object或Array。

The following converts a Map to an Object:

以下将Map转换为Object:

const obj = Object.fromEntries(map)

This will result in the following value of obj:

这将导致以下obj值:


   
   
Output
{firstName: "Luke", lastName: "Skywalker", occupation: "Jedi Knight"}

Now, let’s convert a Map to an Array:

现在,让我们将Map转换为Array:

const arr = Array.from(map)

This will result in the following Array for arr:

这将导致以下用于arr数组:


   
   
Output
[ ['firstName', 'Luke'], ['lastName', 'Skywalker'], ['occupation', 'Jedi Knight'] ]

地图键 (Map Keys)

Maps accept any data type as a key, and do not allow duplicate key values. We can demonstrate this by creating a map and using non-string values as keys, as well as setting two values to the same key.

映射接受任何数据类型作为键,并且不允许重复的键值。 我们可以通过创建映射并将非字符串值用作键,以及将两个值设置为同一键来演示这一点。

First, let’s initialize a map with non-string keys:

首先,让我们使用非字符串键初始化地图:

const map = new Map()

map.set('1', 'String one')
map.set(1, 'This will be overwritten')
map.set(1, 'Number one')
map.set(true, 'A Boolean')

This example will override the first key of 1 with the subsequent one, and it will treat '1' the string and 1 the number as unique keys:

此示例将用后一个覆盖第一个键1 ,并将字符串'1'和数字1视为唯一键:


   
   
Output
0: {"1" => "String one"} 1: {1 => "Number one"} 2: {true => "A Boolean"}

Although it is a common belief that a regular JavaScript Object can already handle Numbers, booleans, and other primitive data types as keys, this is actually not the case, because Objects change all keys to strings.

尽管通常认为常规JavaScript对象已经可以将数字,布尔值和其他原始数据类型作为键进行处理,但实际上并非如此,因为对象将所有键都更改为字符串。

As an example, initialize an object with a numerical key and compare the value for a numerical 1 key and a stringified "1" key:

例如,使用数字键初始化对象,然后比较数字1键和字符串化的"1"键的值:

// Initialize an object with a numerical key
const obj = { 1: 'One' }

// The key is actually a string
obj[1] === obj['1']  // true

This is why if you attempt to use an Object as a key, it will print out the string object Object instead.

这就是为什么如果您尝试使用Object作为键,它将打印出字符串object Object

As an example, create an Object and then use it as the key of another Object:

例如,创建一个对象,然后将其用作另一个对象的键:

// Create an object
const objAsKey = { foo: 'bar' }

// Use this object as the key of another object
const obj = {
  [objAsKey]: 'What will happen?'
}

This will yield the following:

这将产生以下结果:


   
   
Output
{[object Object]: "What will happen?"}

This is not the case with Map. Try creating an Object and setting it as the key of a Map:

地图不是这种情况。 尝试创建一个Object并将其设置为Map的键:

// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')

The key of the Map element is now the object we created.

现在,Map元素的key是我们创建的对象。


   
   
Output
key: {foo: "bar"} value: "What will happen?"

There is one important thing to note about using an Object or Array as a key: the Map is using the reference to the Object to compare equality, not the literal value of the Object. In JavaScript {} === {} returns false, because the two Objects are not the same two Objects, despite having the same (empty) value.

关于使用对象或数组作为键,需要注意一件事:Map使用对象的引用来比较相等性,而不是对象的文字值。 在JavaScript中, {} === {}返回false ,因为尽管两个对象具有相同的(空)值,但它们不是两个相同的对象。

That means that adding two unique Objects with the same value will create a Map with two entries:

这意味着添加两个具有相同值的唯一对象将创建一个包含两个条目的Map:

// Add two unique but similar objects as keys to a Map
map.set({}, 'One')
map.set({}, 'Two')

This will yield the following:

这将产生以下结果:


   
   
Output
Map(2) {{…} => "One", {…} => "Two"}

But using the same Object reference twice will create a Map with one entry.

但是两次使用同一对象引用将创建一个只有一个条目的Map。

// Add the same exact object twice as keys to a Map
const obj = {}

map.set(obj, 'One')
map.set(obj, 'Two')

Which will result in the following:

这将导致以下结果:


   
   
Output
Map(1) {{…} => "Two"}

The second set() is updating the same exact key as the first, so we end up with a Map that only has one value.

第二个set()将更新与第一个相同的确切键,因此我们最终得到的Map只有一个值。

从地图获取和删除项目 (Getting and Deleting Items from a Map)

One of the disadvantages of working with Objects is that it can be difficult to enumerate them, or work with all the keys or values. The Map structure, by contrast, has a lot of built-in properties that make working with their elements more direct.

使用对象的缺点之一是枚举对象或使用所有键或值可能很困难。 相比之下,Map结构具有许多内置属性,这些属性使它们的元素处理更加直接。

We can initialize a new Map to demonstrate the following methods and properties: delete(), has(), get(), and size.

我们可以初始化一个新的Map来演示以下方法和属性: delete()has()get()size

// Initialize a new Map
const map = new Map([
  ['animal', 'otter'],
  ['shape', 'triangle'],
  ['city', 'New York'],
  ['country', 'Bulgaria'],
])

Use the has() method to check for the existence of an item in a map. has() will return a Boolean.

使用has()方法检查地图中是否存在某项。 has()将返回一个布尔值。

// Check if a key exists in a Map
map.has('shark') // false
map.has('country') // true

Use the get() method to retrieve a value by key.

使用get()方法按键检索值。

// Get an item from a Map
map.get('animal') // "otter"

One particular benefit Maps have over Objects is that you can find the size of a Map at any time, like you can with an Array. You can get the count of items in a Map with the size property. This involves fewer steps than converting an Object to an Array to find the length.

与对象相比,地图具有的一个特殊好处是,您可以随时找到地图的大小,就像使用数组一样。 您可以使用size属性获取Map中的项目计数。 与将对象转换为数组以找到长度相比,这涉及的步骤更少。

// Get the count of items in a Map
map.size // 4

Use the delete() method to remove an item from a Map by key. The method will return a Boolean—true if an item existed and was deleted, and false if it did not match any item.

使用delete()方法可通过键从Map删除项目。 该方法将返回一个布尔true如果存在并删除了一个项目,则返回true如果不匹配任何项目,则返回false

// Delete an item from a Map by key
map.delete('city') // true

This will result in the following Map:

这将产生以下地图:


   
   
Output
Map(3) {"animal" => "otter", "shape" => "triangle", "country" => "Bulgaria"}

Finally, a Map can be cleared of all values with map.clear().

最后,可以使用map.clear()清除Map中的所有值。

// Empty a Map
map.clear()

This will yield:

这将产生:


   
   
Output
Map(0) {}

地图的键,值和条目 (Keys, Values, and Entries for Maps)

Objects can retrieve keys, values, and entries by using the properties of the Object constructor. Maps, on the other hand, have prototype methods that allow us to get the keys, values, and entries of the Map instance directly.

对象可以使用Object构造函数的属性来检索键,值和条目。 另一方面,地图具有原型方法,可让我们直接获取Map实例的键,值和条目。

The keys(), values(), and entries() methods all return a MapIterator, which is similar to an Array in that you can use for...of to loop through the values.

keys()values()entries()方法都返回MapIterator ,它与Array相似,因为您可以使用for...of来遍历这些值。

Here is another example of a Map, which we can use to demonstrate these methods:

这是Map的另一个示例,我们可以用来演示这些方法:

const map = new Map([
  [1970, 'bell bottoms'],
  [1980, 'leg warmers'],
  [1990, 'flannel'],
])

The keys() method returns the keys:

keys()方法返回键:

map.keys()

   
   
Output
MapIterator {1970, 1980, 1990}

The values() method returns the values:

values()方法返回值:

map.values()

   
   
Output
MapIterator {"bell bottoms", "leg warmers", "flannel"}

The entries() method returns an array of key/value pairs:

entries()方法返回键/值对的数组:

map.entries()

   
   
Output
MapIterator {1970 => "bell bottoms", 1980 => "leg warmers", 1990 => "flannel"}

地图迭代 (Iteration with Map)

Map has a built-in forEach method, similar to an Array, for built-in iteration. However, there is a bit of a difference in what they iterate over. The callback of a Map’s forEach iterates through the value, key, and map itself, while the Array version iterates through the item, index, and array itself.

Map具有类似于Array的内置forEach方法,用于内置迭代。 但是,它们迭代的内容有所不同。 Map的forEach的回调将迭代valuekeymap本身,而Array版本的回调将迭代itemindexarray本身。

// Map 
Map.prototype.forEach((value, key, map) = () => {})

// Array
Array.prototype.forEach((item, index, array) = () => {})

This is a big advantage for Maps over Objects, as Objects need to be converted with keys(), values(), or entries(), and there is not a simple way to retrieve the properties of an Object without converting it.

这是Maps优于Objects的一大优势,因为Objects需要使用keys()values()entries() ,并且没有简单的方法可以在不进行转换的情况下检索Object的属性。

To demonstrate this, let’s iterate through our Map and log the key/value pairs to the console:

为了说明这一点,让我们遍历地图并将键/值对记录到控制台:

// Log the keys and values of the Map with forEach
map.forEach((value, key) => {
  console.log(`${key}: ${value}`)
})

This will give:

这将给出:


   
   
Output
1970: bell bottoms 1980: leg warmers 1990: flannel

Since a for...of loop iterates over iterables like Map and Array, we can get the exact same result by destructuring the array of Map items:

由于for...of循环遍历Map和Array等可迭代对象,因此我们可以通过分解Map项的数组来获得完全相同的结果:

// Destructure the key and value out of the Map item
for (const [key, value] of map) {
  // Log the keys and values of the Map with for...of
  console.log(`${key}: ${value}`)
}

地图属性和方法 (Map Properties and Methods)

The following table shows a list of Map properties and methods for quick reference:

下表列出了Map属性和方法,以供快速参考:

Properties/MethodsDescriptionReturns
set(key, value)Appends a key/value pair to a MapMap Object
delete(key)Removes a key/value pair from a Map by keyBoolean
get(key)Returns a value by keyvalue
has(key)Checks for the presence of an element in a Map by keyBoolean
clear()Removes all items from a MapN/A
keys()Returns all keys in a MapMapIterator object
values()Returns all values in a MapMapIterator object
entries()Returns all keys and values in a Map as [key, value]MapIterator object
forEach()Iterates through the Map in insertion orderN/A
sizeReturns the number of items in a MapNumber
属性/方法 描述 退货
set(key, value) 将键/值对附加到地图 Map对象
delete(key) 从键中删除键/值对 布尔型
get(key) 通过键返回值
has(key) 通过键检查Map中元素的存在 布尔型
clear() 从地图上删除所有项目 不适用
keys() 返回地图中的所有键 MapIterator对象
values() 返回地图中的所有值 MapIterator对象
entries() [key, value]返回Map中的所有键和值 MapIterator对象
forEach() 按插入顺序遍历Map 不适用
size 返回地图中的项目数

何时使用地图 (When to Use Map)

Summing up, Maps are similar to Objects in that they hold key/value pairs, but Maps have several advantages over objects:

总结起来,地图与对象类似,因为它们拥有键/值对,但地图比对象具有以下优势:

  • Size - Maps have a size property, whereas Objects do not have a built-in way to retrieve their size.

    大小 -地图具有size属性,而对象没有内置的方式来获取其大小。

  • Iteration - Maps are directly iterable, whereas Objects are not.

    迭代 -映射可直接迭代,而对象则不可。

  • Flexibility - Maps can have any data type (primitive or Object) as the key to a value, while Objects can only have strings.

    灵活性 -映射可以具有任何数据类型(原始或对象)作为值的键,而对象只能具有字符串。

  • Ordered - Maps retain their insertion order, whereas objects do not have a guaranteed order.

    有序 -地图保留其插入顺序,而对象没有保证的顺序。

Due to these factors, Maps are a powerful data structure to consider. However, Objects haves some important advantages as well:

由于这些因素,地图是需要考虑的强大数据结构。 但是,对象也具有一些重要的优点:

  • JSON - Objects work flawlessly with JSON.parse() and JSON.stringify(), two essential functions for working with JSON, a common data format that many REST APIs deal with.

    JSON -对象与工作完美JSON.parse()JSON.stringify()与工作两个基本功能JSON ,通用数据格式,许多REST API的处理。

  • Working with a single element - Working with a known value in an Object, you can access it directly with the key without the need to use a method, such as Map’s get().

    使用单个元素 -使用对象中的已知值,您可以使用键直接访问它,而无需使用诸如Map的get()

This list will help you decide if a Map or Object is the right data structure for your use case.

此列表将帮助您确定Map或Object是否适合您的用例。

(Set)

A Set is a collection of unique values. Unlike a Map, a Set is conceptually more similar to an Array than an Object, since it is a list of values and not key/value pairs. However, Set is not a replacement for Arrays, but rather a supplement for providing additional support for working with duplicated data.

集合是唯一值的集合。 与Map不同,Set从概念上讲比对象更像数组,因为它是值的列表,而不是键/值对。 但是,Set并不是阵列的替代品,而是对使用重复数据提供额外支持的补充。

You can initialize Sets with the new Set() syntax.

您可以使用new Set()语法初始化new Set()

const set = new Set()

This gives us an empty Set:

这给了我们一个空集:


   
   
Output
Set(0) {}

Items can be added to a Set with the add() method. (This is not to be confused with the set() method available to Map, although they are similar.)

可以使用add()方法将项目添加到Set中。 (这不要与Map可用的set()方法混淆,尽管它们是相似的。)

// Add items to a Set
set.add('Beethoven')
set.add('Mozart')
set.add('Chopin')

Since Sets can only contain unique values, any attempt to add a value that already exists will be ignored.

由于集合只能包含唯一值,因此将忽略添加任何已存在值的尝试。

set.add('Chopin') // Set will still contain 3 unique values

Note: The same equality comparison that applies to Map keys applies to Set items. Two objects that have the same value but do not share the same reference will not be considered equal.

注意 :与Map键相同的相等性比较也适用于Set项目。 具有相同值但不共享相同引用的两个对象将不被视为相等。

You can also initialize Sets with an Array of values. If there are duplicate values in the array, they will be removed from the Set.

您还可以使用值数组初始化Set。 如果数组中有重复值,则将从集合中将其删除。

// Initialize a Set from an Array
const set = new Set(['Beethoven', 'Mozart', 'Chopin', 'Chopin'])

   
   
Output
Set(3) {"Beethoven", "Mozart", "Chopin"}

Conversely, a Set can be converted into an Array with one line of code:

相反,可以使用一行代码将Set转换为Array:

const arr = [...set]

   
   
Output
(3) ["Beethoven", "Mozart", "Chopin"]

Set has many of the same methods and properties as Map, including delete(), has(), clear(), and size.

Set具有许多与Map相同的方法和属性,包括delete()has()clear()size

// Delete an item
set.delete('Beethoven') // true

// Check for the existence of an item
set.has('Beethoven') // false

// Clear a Set
set.clear()

// Check the size of a Set
set.size // 0

Note that Set does not have a way to access a value by a key or index, like Map.get(key) or arr[index].

请注意,Set无法通过键或索引(例如Map.get(key)arr[index] Map.get(key)访问值。

集的键,值和条目 (Keys, Values, and Entries for Sets)

Map and Set both have keys(), values(), and entries() methods that return an Iterator. However, while each one of these methods have a distinct purpose in Map, Sets do not have keys, and therefore keys are an alias for values. This means that keys() and values() will both return the same Iterator, and entries() will return the value twice. It makes the most sense to only use values() with Set, as the other two methods exist for consistency and cross-compatibility with Map.

Map和Set都具有返回迭代器的keys()values()entries()方法。 但是,尽管这些方法中的每一种在Map中都有不同的用途,但是Set没有键,因此键是值的别名。 这意味着keys()values()都将返回相同的Iterator, entries()将返回该值两次。 仅将values()与Set一起使用是最有意义的,因为存在其他两种方法来实现与Map的一致性和交叉兼容性。

const set = new Set([1, 2, 3])
// Get the values of a set
set.values()

   
   
Output
SetIterator {1, 2, 3}

集迭代 (Iteration with Set)

Like Map, Set has a built-in forEach() method. Since Sets don’t have keys, the first and second parameter of the forEach() callback return the same value, so there is no use case for it outside of compatibility with Map. The parameters of forEach() are (value, key, set).

与Map一样,Set具有内置的forEach()方法。 由于Set没有键,因此forEach()回调的第一个和第二个参数返回相同的值,因此没有与Map兼容的用例。 forEach()的参数是(value, key, set)

Both forEach() and for...of can be used on Set. First, let’s look at forEach() iteration:

forEach()for...of都可以在Set上使用。 首先,让我们看一下forEach()迭代:

const set = new Set(['hi', 'hello', 'good day'])

// Iterate a Set with forEach
set.forEach((value) => console.log(value))

Then we can write the for...of version:

然后我们可以编写for...of版本:

// Iterate a Set with for...of
for (const value of set) {  
    console.log(value);
}

Both of these strategies will yield the following:

这两种策略都将产生以下效果:


   
   
Output
hi hello good day

设置属性和方法 (Set Properties and Methods)

The following table shows a list of Set properties and methods for quick reference:

下表列出了Set属性和方法的列表,以供快速参考:

Properties/MethodsDescriptionReturns
add(value)Appends a new item to a SetSet Object
delete(value)Removes the specified item from a SetBoolean
has()Checks for the presence of an item in a SetBoolean
clear()Removes all items from a SetN/A
keys()Returns all values in a Set (same as values())SetIterator object
values()Returns all values in a Set (same as keys())SetIterator object
entries()Returns all values in a Set as [value, value]SetIterator object
forEach()Iterates through the Set in insertion orderN/A
sizeReturns the number of items in a SetNumber
属性/方法 描述 退货
add(value) 将新项目追加到集合 Set物件
delete(value) 从集合中删除指定的项目 布尔型
has() 检查集中是否有物品 布尔型
clear() 从集合中删除所有项目 不适用
keys() 返回Set中的所有值(与values()相同) SetIterator对象
values() 返回Set中的所有值(与keys()相同) SetIterator对象
entries() 将Set中的所有值返回为[value, value] SetIterator对象
forEach() 按插入顺序遍历Set 不适用
size 返回集合中的项目数

何时使用套装 (When to Use Set)

Set is a useful addition to your JavaScript toolkit, particularly for working with duplicate values in data.

Set是JavaScript工具包的有用补充,特别是在处理数据中的重复值时。

In a single line, we can create a new Array without duplicate values from an Array that has duplicate values.

在一行中,我们可以从没有重复值的数组中创建一个没有重复值的新数组。

const uniqueArray = [ ...new Set([1, 1, 2, 2, 2, 3])] // (3) [1, 2, 3]

This will give:

这将给出:


   
   
Output
(3) [1, 2, 3]

Set can be used for finding the union, intersection, and difference between two sets of data. However, Arrays have a significant advantage over Sets for additional manipulation of the data due to the sort(), map(), filter(), and reduce() methods, as well as direct compatibility with JSON methods.

集合可用于查找两组数据之间的并集,交集和差。 但是,由于有sort()map()filter()reduce()方法以及与JSON方法的直接兼容性,因此与Sets相比,Arrays具有显着的优势。

结论 (Conclusion)

In this article, you learned that a Map is a collection of ordered key/value pairs, and that a Set is a collection of unique values. Both of these data structures add additional capabilities to JavaScript and simplify common tasks such as finding the length of a key/value pair collection and removing duplicate items from a data set, respectively. On the other hand, Objects and Arrays have been traditionally used for data storage and manipulation in JavaScript, and have direct compatibility with JSON, which continues to make them the most essential data structures, especially for working with REST APIs. Maps and Sets are primarily useful as supporting data structures for Objects and Arrays.

在本文中,您了解到Map是有序键/值对的集合,而Set是唯一值的集合。 这两种数据结构都为JavaScript添加了附加功能,并简化了常见任务,例如分别查找键/值对集合的长度和从数据集中删除重复项。 另一方面,对象和数组传统上已用于JavaScript中的数据存储和操作,并且与JSON直接兼容,这继续使它们成为最重要的数据结构,尤其是在使用REST API时。 映射和集合主要用作支持对象和数组的数据结构。

If you would like to learn more about JavaScript, check out the homepage for our How To Code in JavaScript series, or browse our How to Code in Node.js series for articles on back-end development.

如果您想了解有关JavaScript的更多信息,请查看我们的“ 如何在JavaScript中进行编码”系列的主页,或浏览我们的“ 如何在Node.js中进行编码”系列以获取有关后端开发的文章。

翻译自: https://www.digitalocean.com/community/tutorials/understanding-map-and-set-objects-in-javascript

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值