ES6提供了 Map数据结构。它类似于对象,也是键值对的集合。但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。
创建方法
let m = new Map()
console.log(m)
Map的方法
1.set( )
添加元素
接收两个参数,第一个键名,第二个键值
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
console.log(m)
2.size
获取元素个数
let m = new Map()
m.set("name","zs")
console.log(m.size) //1
3.delete( )
删除元素
let m = new Map()
m.set("name","zs")
m.delete("name")
console.log(m)
4.has( )
利用键名去判断
let m = new Map()
m.set("name", "zs")
m.set("age", 18)
console.log(m.has("name")) //true
console.log(m.has("hobby")) //false
5.get( )
获取元素
let m = new Map()
m.set("name","zs")
console.log(m.get("name")) //zs
6.clear( )
清空
let m = new Map()
m.set("name","zs")
m.clear()
console.log(m)
7.entries( )
返回 Map 对象中键/值对的数组
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
console.log(m.entries())
8.keys( )
返回 Map 对象中键的数组
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
console.log(m.keys())
9.values( )
返回 Map 对象中值的数组
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
console.log(m.values())
10.遍历for…of
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
for(let v of m) {
console.log(v)
}
11.forEach
返回键和值回调
let m = new Map()
m.set("name","zs")
m.set("age",18)
let key = {
hobby : "爱好"
}
m.set(key,["唱","跳","rap","篮球"])
m.forEach(item=>{
console.log(item)
})
感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!