15.Map数据类型

1. 定义一个Map数据:

let map=new Map([['name','tom'],['age',12]]);

 

2. Map数据的基本用法:

(1)新增Map数据:

let map=new Map([['name','tom'],['age',12]]);
let newMap=map.set('sex','男');
console.log(newMap); //['name','tom'],['age',12],['sex','男']

(2)获取单元数据:

let map=new Map([['name','tom'],['age',12]]);
let newMap=map.get('age');
console.log(newMap); //12

(3)删除单元:

let map=new Map([['name','tom'],['age',12]]);
let newMap=map.delete('age');
console.log(newMap); //true
console.log(map); //['name','tom']

(4)清除所有单元:

let map=new Map([['name','tom'],['age',12]]);
let newMap=map.clear();
console.log(newMap); //undefined
console.log(map); //[]

(5)循环遍历:

let map=new Map([['name','tom'],['age',12]]);
map.forEach((item,key)=>{
    console.log(item,key); //tom name , 12 "age"
})

(6)判断是否是map单元的键名:

let map=new Map([['name','tom'],['age',12]]);
let newMap = map.has('name');
console.log(newMap); //true

 

3. Map转数组:

let map=new Map([['name','tom'],['age',12]]);
//方法一:
let arr=Array.from(map);
//方法二:
let arr=[...map];
//方法三:
let arr=[];
for(var key of map){
    arr.push(key);
}

 

posted @ 2023-07-06 15:21  cjl2019  阅读(24)  评论(0编辑  收藏  举报