Bootstrap

JavaScript - new Map()基本用法

1 初始化,set 和 get

// 1 new Map(), set and get
const map1 = new Map();

map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
console.log(map1.get('a'));
console.log(map1.get('b'));
console.log(map1.get('c'));

1
2
3

2 size

console.log(map1.size);

3

3 delete

map1.delete('b');

console.log(map1.size);

2

4 has

console.log(map1.has('a'));
console.log(map1.has('b'));

true
false

5 print key, value

for (const [key, value] of map1) {
    console.log(key + ' : ' + value);
}
for (const [key, value] of map1.entries()) {
    console.log(key + " : " + value);
}

a : 1
c : 3

6 print keys, values

for (const key of map1.keys()) {
    console.log(key);
}

for (const value of map1.values()) {
    console.log(value);
}

a
c
1
3

7 forEach

map1.forEach(function (value, key) {
    console.log(key + ' = ' + value)
})

a = 1
c = 3

8 Map 和Array 的相互转化

const keyValue = [['a', 1], ['b', 2]];
const map2 = new Map(keyValue);

console.log(map2.get('a'));
console.log(Array.from(map2));
console.log([...map2]); // spread to array
console.log(Array.from(map2.keys()));

1
[ [ ‘a’, 1 ], [ ‘b’, 2 ] ]
[ [ ‘a’, 1 ], [ ‘b’, 2 ] ]
[ ‘a’, ‘b’ ]

9 map浅拷贝

const original = new Map([
    [1, 'a']
])

const clone = new Map(original)

console.log(clone.get(1))       // a
console.log(original === clone) // false (useful for shallow comparison)

10 map 合并, key相同,保留最后的value

const first = new Map([
    [1, 'a'],
    [2, 'b'],
    [3, 'c'],
])

const second = new Map([
    [1, 'd'],
    [2, 'e']
])

// Merge two maps. The last repeated key wins.
// Spread operator essentially converts a Map to an Array
const merged = new Map([...first, ...second])

console.log(merged.get(1)) // d
console.log(merged.get(2)) // e
console.log(merged.get(3)) // c

d
e
c

;