In ES6, in addition to the addition of set methods, we also consider a scenario of key-value pair storage, and map collection is dedicated to storing the data of multiple key value pairs.
Before maps, we used objects to store key-value pairs, where keys were property names and values were property values. Key – value – data combination is that the key cannot be repeated. Using objects to store keys and values is not desirable in some scenarios:
- The key name can only be a string or symbol, which makes its use very limited
- If you want to know how many data are stored in an object, you have to get all the key names, and then figure out how many properties are in the object by finding the length of the array.
- Key names tend to conflict with names on the stereotype.
How do I create a map
new Map(a);// Create a map collection without any content
new Map(iterable);// Create a map with the initial contents from each iteration of the iterable. However, it requires that the result of each iteration be an array of length 2, with the first item representing the key and the second item representing the value
Copy the code
Example: Create a map collection without any content
const mp = new Map(a);console.log(mp);
Copy the code
Execution Result:
Example: Create a map collection with initial contents
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log(mp);
Copy the code
Execution Result:
1. How to perform subsequent operations
1, size: read-only property, get the number of keys in the current map
Example: the size
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log(mp);
console.log("Total:",mp.size);
Copy the code
Execution Result:
Set (key, value): Sets a pair of keys and values. The keys and values can be of any type
Example: the set ()
const mp = new Map([["a".1], ["b".2], ["c".3]]);
mp.set("d".4)
console.log(mp);
Copy the code
Execution Result:
Note:
- If the key does not exist, an entry is added
- If the key exists, change its value
- The way to check whether the key memory exists is the same as set
Object.is()
Example: How many values are there in the map?
const mp = new Map([["a".1], ["b".2], ["c".3]]);
mp.set({},4);
mp.set("a",abc);
map.set({},00);
console.log(mp);
console.log("Total:",mp.size);
Copy the code
Execution Result:
There are 5 values, the object is the reference value, their address is different, so will not overwrite, and the original value of a 1 will be overwritten by ABC. If you want to use the same reference value object, you can change it like this:
const mp = new Map([["a".1], ["b".2], ["c".3]]);
const obj = {};
mp.set(obj,4);
mp.set("a"."abc");
mp.set(obj,00);
console.log(mp);
console.log("Total:",mp.size);
Copy the code
Execution Result:
3, get(key) : based on a key, get a value
Example: Get (key)
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log("get('a')",mp.get("a"));
Copy the code
Execution Result:
Example: If a key is passed that does not exist
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log("get('a')",mp.get("jasnbdjka"));
Copy the code
Execution Result:
4. Has (key) : Determines whether a key exists
Example: from the ()
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log("has('a')",mp.has("a"));
Copy the code
Execution Result:
5. Delete (key) : Deletes the specified keytrue
, return on failurefalse
Example: delete (key)
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log("delete('a')",mp.delete("a"));
Copy the code
Execution Result:
6. Clear () : Clears the map
Example: the clear ()
const mp = new Map([["a".1], ["b".2], ["c".3]]);
console.log(mp);
Copy the code
2. How to convert to an array
Example: An array is converted to a map collection
// Just put the array in the new Map
const mp = new Map(Array to convert);/ / is as follows:
const mp = new Map([["a".1], ["b".2], ["c".3]]);
Copy the code
Example: Map to array
// Map itself is an iterable object, and the result of each iteration is the value of each item
const mp = new Map([["a".1], ["b".2], ["c".3]]);
const arr = [...mp];
console.log(arr);
Copy the code
Execution Result:
3, traverse
- use
for of
Loop, each iteration yields an array of length 2
Example: the for of
const mp = new Map([["a".1], ["b".2], ["c".3]]);
for (const item of mp) {
console.log(item);
}
Copy the code
Execution Result:
Or you can just deconstruct it
const mp = new Map([["a".1], ["b".2], ["c".3]]);
// Method 1:
for (const [key,value] of mp) {
console.log(key,value);
}
// Method 2:
for (const item of mp) {
console.log(item[0],item[1]);
}
Copy the code
Execution Result:
- use
forEach
traverse
- Parameter 1: The value of each item
- Parameter 2: The key of each item
- Parameter 3: map itself
Example: forEach
const mp = new Map([["a".1], ["b".2], ["c".3]]);
mp.forEach((value,key,that) = >{
console.log(value,key,that);
})
Copy the code
Execution Result:
4. Write a map by hand
The hand-written map method is not the same as the browser-provided map method, because there is no way to call the underlying code, so we need to stretch our thinking.
1. Create the mymap.js file
class MyMap {
constructor(iterable = []) {
// Verify that the object is iterable
this.isIterator(iterable);
this._datas = [];
for (const item of iterable) {
// Item must also be an iterable
this.isIterator(item);
// Fetch the first and second iteration values
const iterator = item[Symbol.iterator]();
const key = iterator.next().value;
const value = iterator.next().value;
this.set(key, value); }}// Determine if it is an iterable
isIterator(target) {
if (typeof target[Symbol.iterator] ! = ="function") {
throw new TypeError(`The ${typeof target} ${target} is not is not iterable (cannot read property Symbol(Symbol.iterator))`); }}/ / set methods
set(key, value) {
const obj = this._getObj(key);
if (obj) {
// If there is a key name, change the value
obj.value = value;
} else {
this._datas.push({
key,
value
})
}
}
//delete
delete(key) {
for (let i = 0; i < this._datas.length; i++) {
const element = this._datas[i];
if (this.isEqual(element.key, key)) {
this._datas.splice(i, 1);
return true; }}return false;
}
/ / get methods
get(key) {
const item = this._getObj(key);
if (item) {
return item.value;
}
return undefined;
}
/ / the size method
get size() {
return this._datas.length;
}
/ / from the method
has(key) {
return this._getObj(key) ! = =undefined; // if undefined, the value is found
}
/ / clear method
clear() {
this._datas.length = 0;
}
//forEach
forEach(callback) {
for (const item of this._datas) {
callback(item.value, item.key, this); }}/** * select * from internal array based on key@param {*} key
*/
_getObj(key) {
for (const item of this._datas) {
if (this.isEqual(item.key, key)) {
returnitem; }}}// Make MyMap itself iterable* [Symbol.iterator]() {
for (const item of this._datas) {
yield [item.key, item.value]
}
}
/** * determine whether two data are equal *@param {*} data1
* @param {*} data2
*/
isEqual(data1, data2) {
// If data1 and data2 are both equal to 0, then we consider them equal
if (data1 === 0 && data2 === 0) {
return true;
}
return Object.is(data1, data2);
}
Copy the code
Code test:
<script src="./js/myMap.js"></script>
<script>
const mp = new MyMap([["a".1], ["b".2], ["c".3]]);
console.log(mp);
</script>
Copy the code
Example: Set method
Example: forEach
<script src="./js/yMap.js"></script>
<script>
const mp = new MyMap([["a".1], ["b".2], ["c".3]]);
mp.forEach((value,key,that) = > {
console.log(value,key,that);
});
</script>
Copy the code
Execution Result:
The above is today’s share, I hope to help you, I also just started to write technical articles, there are a lot of lack of places, I hope nuggets leaders more advice, thank you!!