1.基本的操作:增删改查
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
/* let map=new Map();
map.set('name','yangdongxu');
map.set('age','30');
map.set(function(){},'30');
map.set({},'30');
console.log(map);
console.log(map.size); */
//设置值:
let map=new Map([["name",'怒放的生命'],['height','175']]);
map.set('goods','apple');
map.set('bus','q5');
//判断值是否存在
let j=map.has('goods');
console.log(j);//true
console.log(map.get('goods'));//apple
//删除某个元素
map.delete('bus');
//清除所有元素
map.clear();
</script>
2.遍历数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
let map=new Map([["name",'怒放的生命'],['height','175']]);
map.set('goods','apple');
map.set('bus','q5');
console.log(map.keys());//MapIterator {"name", "height", "goods", "bus"}
console.log(map.values());//MapIterator {"怒放的生命", "175", "apple", "q5"}
console.log(map.entries());//MapIterator {"name" => "怒放的生命", "height" => "175", "goods" => "apple", "bus" => "q5"}
console.log(map);
map.forEach((value,key)=>{
console.log(value,key);
})
/* 怒放的生命 name
demo.html:24 175 height
demo.html:24 apple goods
demo.html:24 q5 bus */
</script>
3.map类型转换操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
//转换操作
let map=new Map([["name",'怒放的生命'],['height','175']]);
map.set('goods','apple');[["name",'怒放的生命'],['height','175']]
map.set('bus','q5');
console.log([...map]);/* (4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ["name", "怒放的生命"]
1: (2) ["height", "175"]
2: (2) ["goods", "apple"]
3: (2) ["bus", "q5"] */
console.log([...map.entries()]);/* (4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ["name", "怒放的生命"]
1: (2) ["height", "175"]
2: (2) ["goods", "apple"]
3: (2) ["bus", "q5"] */
console.log([...map.keys()]);/* ["name", "height", "goods", "bus"] */
console.log([...map.values()]);/* ["怒放的生命", "175", "apple", "q5"]*/
for( let [key,val] of map){
console.log(key,val);
}
/*
name 怒放的生命
demo.html:32 height 175
demo.html:32 goods apple
demo.html:32 bus q5
*/
//获取指定值的map数据
let newArr=[...map].filter((item)=>{
return item[1].includes('apple')
})
console.log(newArr);
let getData=new Map(newArr);
console.log([...getData.values()]);//['apple']
</script>