Javascript 简明教程
JavaScript - The Maps Object
Map object 在 JavaScript 中是键值对的集合,其中键可以是任何类型的,包括对象或函数。映射元素的顺序与键值对的插入顺序相同。
A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs.
要创建一个新的 Map 对象,可以使用 new Map() 构造函数。然后,可以使用 set() 方法向映射中添加键值对。要获取特定键的值,可以使用 get() 方法。要从映射中移除键值对,可以使用 delete() 方法。
To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method.
Syntax
以下是 JavaScript 中使用 Map 数据结构的语法:
Following is the syntax to use the Map data structure in JavaScript −
const map = new Map([iterable]);
在上述语法中,我们使用带有 Map() 构造函数的“new”关键字来定义 Map 的实例。
In the above syntax, we used the 'new' keyword with a Map() constructor to define an instance of the Map.
Parameters
-
iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter.
JavaScript 中的 Map 类包含一组内置方法,让我们能够使用 Map 对象。在此,我们列出了 Map 的属性和方法。
The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map.
Map Properties
以下是 Map 对象的属性:
Following are the properties of Map object −
Sr.No. |
Name & Description |
1 |
size This property returns the number of elements in this map. |
Map Methods
在下面的表格中,我们列出了 Map 对象的所有方法及其说明:
In the following table, we have listed all the methods of Map object and their description −
Sr.No. |
Name & Description |
1 |
clear() This method removes all elements from a Map object. |
2 |
delete() This method removes a specified element from a Map object by key. |
3 |
entries() This method returns a new map iterator object that contains the [key, value] pairs. |
4 |
forEach() This method executes a callback function once per each key/value pair in a Map object. |
5 |
get() This method is used to return a specified element from a Map object. |
6 |
has() This method indicates whether an element with the specified key exists or not. |
7 |
keys() This method returns a new Iterator object that contains the keys for each element in the Map object. |
8 |
set() This method insert the key-value pair to a Map object. |
9 |
values() This method returns a new Iterator object that containing values of the Map object. |
JavaScript Map Constructor()
以下是在 JavaScript 中的 Map 的构造函数——
Following is the constructor of Map in JavaScript −
Sr.No. |
Name & Description |
1 |
Map() To create a Map object. |
Examples
Example: Creating new Map Object
在下面的示例中,我们传递了一个包含键值对的二维数组作为 Map() 构造函数的参数。
In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor.
在那之后,我们遍历 map 以获取 map 的每个值并在输出中展示。
After that, we traverse the map to get each value of the map and show in the output.
<html>
<body>
<div> Map elements are: </div>
<div id = "output"> </div>
<script>
const map = new Map([["Apple", 100], ["Banana", 20], ["Orange", 50]]);
for (let [key, value] of map) {
document.getElementById("output").innerHTML += `${key} : ${value} <br>`;
}
</script>
</body>
</html>
在执行上述程序后,它将返回 map 的每个值。
After executing the above program, it returns each value of the map.
Map elements are:
Apple : 100
Banana : 20
Orange : 50
Example: Inserting key-value pair in the Map
在下面的示例中,我们使用 set() 方法在 map 中插入键值对。set() 方法将键作为第一个参数,并将值作为第二个参数。
In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument.
<html>
<body>
<div>After inserting 2 key-value pairs in the map: </div>
<div id = "output"> </div>
<script>
const map = new Map();
map.set("Grapes", 40);
map.set("Apples", 50);
for (let [key, value] of map) {
document.getElementById("output").innerHTML += `${key} : ${value} <br>`;
}
</script>
</body>
</html>
After inserting 2 key-value pairs in the map:
Grapes : 40
Apples : 50
正如我们可以在输出中看到的那样,提供的 [key-value] 对已插入到 Map 对象中。
As we can see in the output, the provided [key-value] pairs have been inserted in the Map object.
Example: Accessing Map Elements
可以 get() 方法来访问 map 元素。在这里,我们在 set 中添加了元素。
The get() method can be used to access the map elements. Here, we have added elements to the set.
在那之后,我们使用 get() 方法来访问 name 和 RollId 键的值。
After that, we used the get() method to access the values of the name and RollId keys.
<html>
<body>
<div id = "output1">Name: </div>
<div id = "output2">Roll Id: </div>
<script>
const map = new Map();
map.set("name", "John");
map.set("rollId", 123);
document.getElementById("output1").innerHTML += map.get("name");
document.getElementById("output2").innerHTML += map.get("rollId");
</script>
</body>
</html>
在执行后,它将返回 Map 对象中存在的所有元素。
After executing, it returns all the elements present in the Map object.
Name: John
Roll Id: 123
Example: Removing a Map Element
在下面的示例中,我们使用 delete() 方法删除键值为 20 的键值对。
In the example below, we use the delete() method to delete the key-value pair having a key 20.
但是,你还可以使用 clear() 方法从 map 中删除所有元素。
However, you can also use the clear() method to remove all elements from the map.
<html>
<body>
<div>Map after deleting the [20,30] key-value pair: </div>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
const map = new Map([[10, 20], [20, 30], [30, 40]]);
map.delete(20); // Deleting a [20,30] key-value pair from the map
for (let [key, value] of map)
output.innerHTML += "Key: " + key + " Value: " + value + "<br/>";
</script>
</body>
</html>
Map after deleting the [20,30] key-value pair:
Key: 10 Value: 20
Key: 30 Value: 40
Example: Size of the Map
在下面的代码中,我们使用了 Map 类的 size 属性来获取 map 中键值对的总数。
In the below code, we used the 'size' property of the Map class to get the total number of key-value pairs in the map.
<html>
<body>
<p id = "output">Size of the map object is: </p>
<script>
const map = new Map();
map.set("Grapes", 40);
map.set("Apples", 50);
document.getElementById("output").innerHTML += map.size;
</script>
</body>
</html>
Size of the map object is: 2
Example: Use object as a key
map 允许开发者使用对象作为键。在这里,我们定义了一个包含两个属性的 laptop 对象。
The map allows developers to use the object as a key. Here, we have defined the laptop object containing two properties.
在那之后,我们将对象设为键,并将笔记本的价格设为 map 中的值。
After that, we set the object as a key and the laptop’s price as a value in the map.
<html>
<body>
<p id = "output">The laptop price is: </p>
<script>
const map = new Map();
const laptop = {
brand: "HP",
model: "Pavilion",
}
map.set(laptop, 100000);
document.getElementById("output").innerHTML += map.get(laptop);
</script>
</body>
</html>
The laptop price is: 100000
Map vs. Object in JavaScript
Map 类似于 JavaScript 中的对象,但这里有一些我们已解释过的不同——
A Map is similar to the Object in JavaScript, but there are some differences which we have explained here −
Basis of Comparison |
Map |
Object |
Keys |
The map allows you to set the object, function, and other primitive values as a key. |
The Object can contain only a string and a symbol as a key. |
Size |
You can get the size of the map using the 'size' property. |
You need to traverse through the object to determine the size of the object. |
Key comparison |
It uses flexible methods to compare the keys. It considers two similar objects with different references different. |
It implicitly converts the keys into the string and matches them. |
Iteration |
You can use the for…of loop to traverse the map. |
You can use the for…in loop to traverse the object properties. |
Performance |
The map is slightly slower due to its complex structure. |
The object is faster than the map as it only stores keys in the string format. |
Use cases |
The map is the better option to use for adding key-value pairs dynamically. |
The object is better to use if key-value pairs are static and fixed. |