Take you to easily understand the Map of the data structure

Preface

Original intention: I was reading the book "In-depth Understanding of Es6" recently . I didn't fully learn Es6 grammar before. I also took advantage of the busy stage to re-read and sort out the notes to share with everyone. If you don't like it, don't spray.

Suitable for the crowd: the front-end primary development, the big guys detour.

Content structure: Know Map -> Basic Usage -> Application Scenarios

The Map structure is similar to the set structure syntax we explained in the previous section "Understanding the Set of Data Structures, It Only Takes 5 Minutes" . The difference is that Map syntax is an array key-value pair format, and Map also handles the problem of preventing object key-value forced type conversion. Map is solved by using the characteristics of arrays. We all know that arrays can be passed in any type of value, so the Map structure also receives all types of values. We just said that the value will not be forced to type as the object. For example, 24 and "24" are two types of relationship, which will not affect each other.

Basic grammar

Map.set add

let map = new Map()
map.set("name", "蛙人")
console.log(map)

In the above example, an Mapobject is created . As we said above, it Mapis an array object. It also receives an array object, which is a two-dimensional array. The parameters inside are in the form of key-value pairs, and then the mapvalue is set . The map.setmethod receives two parameters, the former The keylatter is the valuevalue. At this time, the Map object has added a namevalue

Map.size length

let map = new Map()
map.set("name", "蛙人")
console.log(map.size) // 1

In the above example, the Mapobject provides viewing sizeattributes to view Mapseveral sets of data in the current structure.

Map.get get

let map = new Map()
map.set("name", "蛙人")
console.log(map.get("name")) // 蛙人

In the above example, we use the Map.getmethod to get the attribute value of the object. If you get an Mapobject that does not exist, return undefined.

Map.has query

let map = new Map()
map.set("name", "蛙人")
console.log(map.has("name")) // true

In the above example, what is Map.hasreturned is a Booleanvalue, and it will be Mapsearched in this if it is found and returned true, otherwise it will be returned false, which is generally used to detect the existence of the value in this Map.

Map.delete delete

let map = new Map()
map.set("name", "蛙人")
console.log(map.delete("name")) // true

In the above example, the Map.deletemethod deletes a value in the Mapstructure, and returns if the value exists in the structure, and returns trueif it deletes a non-existent value false.

Map.clear clear

let map = new Map()
map.set("name", "蛙人")
map.clear()

In the above example, Map.clearthis method will clear Mapall the attributes in the structure.

Map uses forEach

let map = new Map([
    ["name", "蛙人"],
    ["age", 24],
    ["sex", "male"]
])

map.forEach((value, key, self) => {
    
    
    console.log(value, key, self) 
})

In the above example, you can see that the Mapstructure is a two-dimensional array, which is in the form of key-value pairs. The Map structure can also be traversed using forEach, which receives 3 parameters:

  • The value of the object
  • The key value of the object
  • Object itself

Note: This is different from the Set structure. The first two parameters of the Set structure are object values. That is because the Set structure does not have the concept of a key value.

Map quickly convert objects

We mentioned above that it Mapcan be forEachtraversed, so that loop analysis can also form a new object. Then the Es6 method provides a new way to quickly convert this structure into an object.

let map = new Map([
    ["name", "蛙人"],
    ["age", 24],
    ["sex", "male"]
])
console.log(Object.fromEntries(map)) // {name: "蛙人", age: 24, sex: "male"}

In the above example, the data structure of Map can be quickly converted into a traditional object literal format. You can also read my article "Summary | What features does Es6 object extend?"

The difference between Set structure and Map structure

One sentence summary: The Set structure is mainly used to determine whether a value exists in the object, and the Map structure is mainly used to obtain the value of the object from the current structure.

Application scenarios

Data cache

In some cases, we need to realize it. I request the backend interface API for the first time, and after I request it, I will cache it for the second time, instead of sending the interface API.

let map = new Map()
function fn() {
    
    
    if (!map.has("api")) {
    
    
        let res = axios.get("api")
        map.set("api", res.data)
        return res.data
    } else {
    
    
	return map.get("api")
    }
}
fn()

Abandoned if else man

When we are in project requirements, we will definitely encounter a state corresponding to an operation, as follows:

let text = ""
if (status == 1) {
    
    
    text = "启用"
} else if (status = 2) {
    
    
    text = "停用"
}
// 省略...

// 以上我们需要写一堆的 if else这样代码非常的繁琐冗余


let operation = new Map([
    [1, "启用"],
    [2, "停用"],
    [3, "注销"]
])
text = operation.get(status) // 这样实现代码非常简洁

thank

Thank you for opening this article during your busy schedule. I hope it will be helpful to you. If you have any questions, you are welcome to correct me.

I’m a frogman, if you think it’s ok, please give me a thumbs up.

Interested friends can join [Front-end entertainment circle exchange group] Welcome everyone to communicate and discuss

High praise and good articles in the past

"Do you know all the JavaScript tips used in these jobs?"

"Understanding the set of data structure, as long as 5 minutes!

"[Recommended Collection] Share some commonly used Git commands in work and how to solve special problem scenarios"

"Deconstruction: Make data access more convenient!

"Do you really understand the features of ES6?

"The difference between var, let, and const that you can understand at a glance"

Guess you like

Origin blog.csdn.net/weixin_44165167/article/details/114625727