Usage of new Map in JavaScript

Map in JavaScript is a data structure based on key-value pairs, which can be used to store and process data. Here are some common Map usages:

create map

A Map can be created using a constructor or a literal . When using the constructor, an iterable object can be passed in as a parameter, which contains a set of key-value pairs. When using the literal method to create, you need to enter a set of key-value pairs in braces, and each key-value pair is separated by commas.

// 使用构造函数创建Map
const myMap1 = new Map([['key1', 'value1'], ['key2', 'value2']]);

// 使用字面量方式创建Map
const myMap2 = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

Add and get elements

You can use the set() method to add a key-value pair to the Map, and use the get() method to get the value corresponding to the specified key

const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

console.log(myMap.get('key1')); // 输出value1
console.log(myMap.get('key2')); // 输出value2

delete element

You can use the delete() method to delete a key-value pair in the Map, and use the clear() method to clear the entire Map.

const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

myMap.delete('key1'); // 删除key1对应的键值对
console.log(myMap.get('key1')); // 输出undefined

myMap.clear(); // 清空整个Map
console.log(myMap.size); // 输出0

Traversing the Map

You can use the for...of loop, the forEach() method, or the entries() method to iterate over all key-value pairs in the Map.

const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

// 使用for...of循环遍历Map
for (const [key, value] of myMap) {
  console.log(key, value);
}

// 使用forEach()方法遍历Map
myMap.forEach((value, key) => {
  console.log(key, value);
});

// 使用entries()方法遍历Map
for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

Determine whether the Map contains a key or value

You can use the has() method to determine whether a key is contained in the Map, and the includes() method to determine whether a value is contained in the Map.

const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

console.log(myMap.has('key1')); // 输出true
console.log(myMap.includes('value2')); // 输出true

 The above are several common Map usages, which can be selected according to the specific situation.

Guess you like

Origin blog.csdn.net/weixin_69811594/article/details/131701606