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.get( )
获取元素
let m = new Map()m.set("name","zs")console.log(m.get("name")) //zs
5.clear( )
清空
let m = new Map()m.set("name","zs")m.clear()console.log(m)
6.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())
7.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())
8.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())
9.遍历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)}
10.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)})
感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!