Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Map class
Map Object data structure. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys.
Reference types including NULL/undefined/ NaN, objects and arrays can be used as keys and values!
You can use the new Map() constructor to create a Map Map object
let emptyMap = new Map(a)// Create a new empty map
// Create a new mapping from the string 'one' to the number 1
let firstMap = new Map([["one".1],
["two".1]])Copy the code
A Map object can also be thought of simply as an array. We know that arrays are indexed by consecutive integers starting at 0. Map objects are not limited to consecutive integers as keys, but can use any value as’ index ‘; Like arrays, maps Map quickly, no matter how large the Map is, to query the value associated with a key. I think after all, the index of the array is simple integer and continuous bar, I don’t know if we can compare this oh?
let copyMap = new Map(n) // Create a new mapping that has the same key and value as' n 'and is used as' copy'
let obj = {x: 1.y: 2} // An object with two attributes
let mapFromObj = new Map(Object.entries(obj)) // ==> new Map([["x", 1], ["y", 2]])
Copy the code
Map related methods
.size
===> similar to an arraylength
.set()
===> Set the key-value pair.get()
===> Obtain the mapping value by key name.has()
===> Check whether the query key exists. Returns true; If not, return false.delete()
= = = > delete.clear()
===> Delete Clears all key-value pairs
Query to access and set the value of a Map object
let newmap = new Map()
newmap.size // 0, this is an empty mapping, size is 0
newmap.set("one".1) // The set method sets the mapping key "one" and the value 1
newmap.set("two".2) // The set method adds the key "two" and the value 2
newmap.size // 2 After the setting above, the mapping now has two keys size 2
newmap.get("two") // 2 // get method, get value by key name
newmap.get("one") / / 1
newmap.get("three") // undefined because there is no key name three returns undefined
newmap.has("one") // true contains the key "one"
newmap.has("three") // false does not contain the key "three", returns false
newmap.delete("one") // Delete the key pair "one"
newmap.clear() // Clear all key-value pairs
Copy the code
And the.set() method here is like a pipe and can also be called consecutively
newmap.set("three".3).set("four".4)
Copy the code
Other iterative methods
.keys()
===> Iteration key key.values()
===> only iterates over the value of the map.entries()
===> iterates key and value, similar to.
forEach
===> Map objects can also be mapped iteratively using the forEach() method