1、为什么会有Map结构?
JavaScript中的对象只能用字符串当作键。为了解决这个问题,ES6提出了Map数据结构。
2、Map结构是什么?
它是键值对的集合,类似于对象,各种类型的值都可以当作键。
Map构造函数接受数组作为参数。
const map = New Map([
['name','kobe'],
['age',18],
]);
不仅仅是数组,任何可迭代、且每个成员都是一个双元素的数组的数据结构都可以当作Map构造函数的参数。
3、Map的属性和操作方法
- size:返回Map的成员总数
- Map.prototype.set(key,value): 设置键值的方法
- Map.prototype.get(key): 读取键对应的值
- Map.prototype.has(key): 判断某个键是否再当前Map对象中
- Map.prototype.delete(key): 删除某个键
- Map.prototype.clear(): 清除所有成员
const map = new Map();
map.set('name','kobe'); // 键是字符串
map.set(18,'age'); // 键是数值
map.set(undefined,'nah'); // 键是undefined
map.size // 3
map.get('name') // kobe
map.has('name') // true
map.has('class') // false
map.delete('name')
map.has('name') // false
map.size //2
map.clear()
map.size //0
4、遍历方法
- Map.prototype.keys(): 返回键名的遍历器
- Map.prototype.values(): 返回键值的遍历器
- Map.prototype.entries(): 返回所有成员的遍历器
- Map.prototype.forEach(): 遍历Map的所有成员
const map = new Map([
['F','no'],
['T','yes'],
]);
for(let key of map.keys()){
console.log(key);
}
// 'F'
// 'T'
for(let value of map.values()){
console.log(value)
}
// 'no'
// 'yes'
for(let item of map.entries()){
console.log(item[0],item[1]);
}
// 'F' 'no'
// 'T' 'yes'
// 或者
for(let [key,value] of map.entries()){
console.log(key,value);
}
// 'F' 'no'
// 'T' 'yes'
// 等同于
for (let [key,value] of map){
console.log(key,value);
}
// 'F' 'no'
// 'T' 'yes'
// Map结构的默认遍历器接口就是entries方法。
5、与其他数据结构的互相转换
(1) Map转数组
最方便的方式是使用扩展运算符(...)
const map = new Map([ [1,'one'],
[2,'two'],
[3,'three'],
]);
[...map.keys()]
// [1,2,3]
[...map.values()]
// ['one', 'two' , 'three']
[...map.entries()]
// [[1,'one],[2,'two'],[3,'three']]
[...map]
// [[1,'one],[2,'two'],[3,'three']]
(2) 数组转Map
new Map([
[true,7],
[{foo: 3},['abc']]
])
/*
Map {
true => 7,
Object {foo: 3} => ['abc']
}
*/
(3)Map转对象
function strMapToObj(strMap){
let obj = {};
for(let [k,v] of strMap){
obj[k] = v;
}
return obj;
}
(4) 对象转Map
let obj = {name: 'kobe',age: 18};
let map = new Map(Object.entries(obj));
6、weakMap与Map的区别
- WeakMap只接受对象作为键名
- WeakMap的键名所指向的对象,不计入垃圾回收机制
const wm1 = new WeakMap();
const key = {foo:1};
wm1.set(key,2);
wm1.get(key); // 2
wm1.set(1,2)
// TypeError: 1 is not an object!
wm1.set(Symbol(),2)
// TypeError: Invalid value used as weak map key
wm1.set(null,2)
// TypeError: Invalid value used as weak map key
.........