[Interview Question] Detailed explanation of Map() in JavaScript

 Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

Map() in JavaScript

JavaScript is a dynamic, interpreted programming language used to develop dynamic pages and interactive applications on the web. Compared with other programming languages, JavaScript has more flexible built-in data types, and has a higher level of debugging and error handling facilities. One of the core features of JavaScript is its built-in Map() data structure. This article will introduce Map() in JavaScript in detail.

Definition and basic use of Map()

Map() is a data structure built into JavaScript that allows you to map key-value pairs to arbitrary types of values. The use of Map() is very simple, you can create a new Map() instance in the following way.

const myMap = new Map();

You can now add elements to the Map() using the set() method. The set() method accepts two parameters: key and value.

myMap.set("key1", "value1");
myMap.set("key2", "value2");

Here, we map the strings "key1" and "key2" to the values ​​"value1" and "value2" respectively.

To retrieve a value from a Map(), you can use the get() method, which accepts a key as an argument.

console.log(myMap.get("key1")); //输出:"value1"

If you want to get all the keys or all the values ​​in the Map(), you can use the keys() or values() methods which return an iterator.

console.log([...myMap.keys()]); //输出:["key1", "key2"]
console.log([...myMap.values()]); //输出:["value1", "value2"]

Advanced Features of Map()

In addition to the basic addition and retrieval of elements, Map() also provides some other powerful functions, which can be very useful in some situations.

Any type can be used as a key

Unlike objects, Map() can use any type as a key, including functions, arrays, objects, or even other Map() instances. This makes Map() very flexible.

const myFunc = () => console.log("Hello World!");
const myArray = [1, 2, 3];
const myObject = {name: "John Doe", age: 30};

const myMap = new Map();

myMap.set(myFunc, "Function value");
myMap.set(myArray, "Array value");
myMap.set(myObject, "Object value");

console.log(myMap.get(myFunc)); //输出:"Function value"
console.log(myMap.get(myArray)); //输出:"Array value"
console.log(myMap.get(myObject)); //输出:"Object value"

Easy to iterate over all elements

Map() provides an entries() method that returns an iterator containing key/value pairs for all elements in the Map().

for (let [key, value] of myMap.entries()) {
  console.log(key, value);
}

//输出:
//myFunc() "Function value"
//[1, 2, 3] "Array value"
//{name: "John Doe", age: 30} "Object value"

Easy to detect if element exists

Map() provides a has() method that takes a key and returns a boolean indicating whether the key exists in the Map().

console.log(myMap.has(myFunc)); //输出:true
console.log(myMap.has("non-existent key")); //输出:false

easy to remove elements

Similar to the set() method, Map() also has a delete() method that can be used to delete the specified key and its associated value from the Map().

myMap.delete(myFunc);
console.log(myMap.has(myFunc)); //输出:false

Has extensible properties and methods

Map() objects are extensible and allow you to override any property or method to suit your needs. For example, you could extend Map() to include a "clear()" method.

class MyMap extends Map {
  clear() {
    console.log("Clearing the map!");
    super.clear();
  }
}

const myMap = new MyMap();

myMap.set("key1", "value1");
myMap.set("key2", "value2");

myMap.clear(); //输出:"Clearing the map!"

Usage scenario of Map()

Although Map() may not be as common as other JavaScript data structures such as objects or arrays, it can be very useful in certain situations.

cache data

Map() is good for use as a cache because the underlying data structure of key/value pairs is very fast and easy to retrieve and update.

const cache = new Map();

function getSomeData(id) {
  if (cache.has(id)) {
    return cache.get(id);
  } else {
    const data = fetchDataFromServer(id);
    cache.set(id, data);
    return data;
  }
}

loop with key

Map() makes it very easy to use keys in loops, which is useful when you need to iterate over multiple arrays or objects.

const myMap = new Map();

myMap.set("key1", "value1");
myMap.set("key2", "value2");

for (let [key, value] of myMap) {
  console.log(key, value);
}

//输出:
//key1 "value1"
//key2 "value2"

translate text

Fast and customizable translation of text is possible using Map(). Put all the text in a Map(), and then select the translation corresponding to the key according to the current language.

const translations = new Map([
  ["Hello", {
    "en-US": "Hello",
    "zh-CN": "你好",
    "fr-FR": "Bonjour"
  }],
  ["Goodbye", {
    "en-US": "Goodbye",
    "zh-CN": "再见",
    "fr-FR": "Au revoir"
  }]
]);

function translate(text, language) {
  return translations.get(text)[language];
}

console.log(translate("Hello", "zh-CN")); //输出:"你好"

in conclusion

Map() is a fast, flexible data structure in JavaScript that supports arbitrary types of keys and extensible properties and methods. It is useful in many situations, including caching data, looping with keys, and text translation. If you need a fast and flexible data structure for storing and retrieving key-value pairs, consider using Map() in JavaScript.

 

Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/132458282