一、map的特点
JavaScript 的对象(Object),本质上是键值对的集合(Hash 结构),但是传统上只能用字符串当作键。这给它的使用带来了很大的限制。
为了解决这个问题,ES6 提供了 Map 数据结构。它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。也就是说,Object 结构提供了“字符串—值”的对应,Map 结构提供了“值—值”的对应,是一种更完善的 Hash 结构实现。如果你需要“键值对”的数据结构,Map 比 Object 更合适。
let m = new Map(); let myInfo = {name: 'shangyy', age: 18}; console.log(m.set(myInfo,'person')); // Map { { name: 'shangyy', age: 18 } => 'person' } console.log(m.get(myInfo)); // person console.log(m.has(myInfo)); // true console.log(m.size); // 1 m.delete(myInfo) console.log(m) // Map {}
let m= new Map([ ['name', 'shangyy' ], ['age', 18], ]) console.log(m) // Map { 'name' => 'shangyy', 'age' => 18 } // 实现原理 let m1 = new Map(); let lists=[ ['name', 'shangyy' ], ['age', 18], ]; lists.forEach(([key,value]) => { m1.set(key,value); }); console.log(m1); // Map { 'name' => 'shangyy', 'age' => 18 }
let m= new Map(); console.log(m.set(1,'aaa').set(1,'bbb').get(1)); // bbb console.log(m.set([1],'aaa').get([1])); // undefined
let m = new Map([ [{identity:'master', status: 1}, ()=>{console.log('master-1');}], [{identity:'master', status: 2}, ()=>{console.log('master-2');}], [{identity:'gester', status: 1}, ()=>{console.log('gester-1');}], [{identity:'gester', status: 1}, ()=>{console.log('gester-2');}], ]); console.log(m); // Map { // { identity: 'master', status: 1 } => [Function], // { identity: 'master', status: 2 } => [Function], // { identity: 'gester', status: 1 } => [Function], // { identity: 'gester', status: 1 } => [Function] } console.log([...m]); // [ [ { identity: 'master', status: 1 }, [Function] ], // [ { identity: 'master', status: 2 }, [Function] ], // [ { identity: 'gester', status: 1 }, [Function] ], // [ { identity: 'gester', status: 1 }, [Function] ] ]
/* type: football、basketball status: 1-开始, 2-进行中 3-结束 */ const actions=()=>{ return new Map([ ['football_1',()=>{console.log('football_1')}], ['football_2',()=>{console.log('football_2')}], ['football_3',()=>{console.log('football_3')}], ['basketball_1',()=>{console.log('basketball_1')}], ['basketball_2',()=>{console.log('basketball_2')}], ['basketball_3',()=>{console.log('basketball_3')}], ]); } const onHandleClick=(type, status)=>{ const action = [...actions()].filter(([key,value])=>{ return key === `${type}_${status}` }) action.forEach(([key,value])=>{ value.call(this); }) } onHandleClick('football',2)