普通的object对象是键值对的集合,但对于它的键却有着严苛的要求,必须是字符串,这给我们平时带来很多的不方便
Map函数类似于对象,但它是一个更加完美的简直对集合,键可以是任意类型
- set()方法可以向map实例对象中添加一组键值对
let a=new Map(); let key={name:"ww",sex:"man"}; a.set(key,'ABC'); console.log(a)//{{name:"ww",sex:"man"}=>"ABC"} let b=new Map(); b.set('name','zhangsan'); console.log(b)//{'name'=>'zhangsan'}
- get()方法可以向map对象获取一个属性值
let a=new Map(); let key={name:"ww",sex:"man"}; a.set(key,'ABC'); console.log(a.get(key))//'ABC'
- has()方法检测map对象中是否存在某个属性,返回bool
- delete()方法删除map对象中某个键,返回bool
let a=new Map(); let key={name:"ww",sex:"man"}; a.set(key,'ABC'); console.log(a.has(key))//true a.delete(key); console.log(a.has(key))//false
- Map()函数接受数组作为参数,最少必须是二维双数组,长度为2
let a=new Map([['name','wangwei'],['sex','man']]); console.log(a)//{'name'=>'wangwei','sex'=>'man'} let b=new Set([['a','A'],['b','B']]); let c=new Map(b); console.log(c)//{'a'=>'A','b'=>'B'}
- Map()函数接受iterator接口,Map可以自己赋值,注意:不可以对象初始化Map
let b=new Set([['a','A'],['b','B']]); let c=new Map(b); let d=new Map(c); console.log(d)
- Map函数初始化,注意:数组引用必须相同才会覆盖
let a=['a','A']; let b=['a','A']; let c=new Map(); c.set(a,1); c.set(b,2); console.log(c.get(a),c.get(b))// 1 2
let a=['a','A']; let b=a; let c=new Map(); c.set(a,1); c.set(b,2); console.log(c.get(a),c.get(b))// 2 2
- size属性获取map对象成员个数
- clear()属性清除map对象的成员
- forEach()遍历
- keys()
- entries()
- values()
let a=new Map([[1,'a'],[2,'b'],[3,'c']]); for(let i of a){ console.log(i) } //[1,'a'],[2,'b'],[3,'c'] for(let i of a.keys()){ console.log(i) }//1 2 3 for(let i of a.values()){ console.log(i) }//a b c for(let [key,value] of a.entries()){ console.log(key,value) }//1 'a' 2 'b' 3 'c'
- Map转换为数组 方法 ...|...keys()|...values|...entries
let a=new Map([[1,'a'],[2,'b'],[3,'c']]); let b=[...a]; console.log(b)//[[1,'a'],[2,'b'],[3,'c']] let c=[...a.keys()]; console.log(c)//[1,2,3] let d=[...a.values()]; console.log(d);//["a", "b", "c"] let e=[...a.entries()]; console.log(e);//[[1,'a'],[2,'b'],[3,'c']]
- Map对象转换为对象,注意:Map的键必须全部是字符串
let a=new Map([['a','A'],['b','B'],['c','C']]); let b={}; for(let [key,value] of a){ b[key]=value } console.log(b)//{a: "A", b: "B", c: "C"}
- 对象转换为Map
let a=new Map(); let b={a: "A", b: "B", c: "C"}; for(let i in b){ a.set(i,b[i]) } console.log(a)//{"a" => "A", "b" => "B", "c" => "C"}
- JSON转对象,可以先转换为数组或者对象再转换为map
- weakMap()键必须是对象