Map数据结构是一种类似于对象的键值对数据结构,不同于对象的是Map的健可以为任意类型的值,而不仅仅为字符串。
Map的基本用法
创建一个名为m的Map数据结构的变量。
let m = new Map();
Map对象的操作方法
![](http://ywhblog.top/wp-content/uploads/2021/08/image-6.png)
Map对象的遍历方法
![](http://ywhblog.top/wp-content/uploads/2021/08/image-7.png)
Map中的keys()和values()方法
m.set("名字","张三")
.set({},"李四")
.set("年龄","23");
for(let key of m.keys()){
log(key);
}
log("-----------")
for(let value of m.values()){
log(value);
}
输出
![](http://ywhblog.top/wp-content/uploads/2021/08/image-8-1024x267.png)
Map对象的entries方法
let m = new Map();
m.set("名字","张三")
.set({},"李四")
.set("年龄","23");
for(let [key,value] of m.entries()){
log(key+"==>"+value);
}
输出
![](http://ywhblog.top/wp-content/uploads/2021/08/image-9.png)
Map对象的forEach方法
let log=console.log;
let m = new Map();
m.set("名字","张三")
.set({},"李四")
.set("年龄","23");
m.forEach((value,key,map)=>{
log("key: %s ==> value: %s",key,value);
})
输出
![](http://ywhblog.top/wp-content/uploads/2021/08/image-10.png)