<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>map数据结构</title>
</head>
<body>
<script>
/**
* 数据结构:map
* 键值对:与对象不同的是键和值可以是任何类型
*/
const map1 = new Map();
//设置key键
const key1 = "some string",
key2 = {},
key3 = function () {}
// 为key设置value值
map1.set(key1,'Value of key1');
map1.set(key2,'Value of key2');
map1.set(key3,'Value of key3');
// 根据key值获取对应的value
console.log(map1.get(key1));
// 获取对应的value数量
console.log(map1.size);
// for ....of遍历map1中的key and value
for(let [key,value] of map1){
console.log(`${key} = ${value}`);
}
// for .. of遍历map1中的key
for(let key of map1.keys()){
console.log(key);
}
// for .. of 遍历map1中的value
for(let value of map1.values()){
console.log(value);
}
// forEach遍历map1
map1.forEach((value,key) =>{
console.log(`${key} = ${value}`);
})
// 将map1转化为正常的数组
const keyValueArray = Array.from(map1);
console.log(keyValueArray);
// 将map1中的key转化为数组
let keyArray = Array.from(map1.keys());
console.log(keyArray);
// 将map1中的value转化为数组
let valueArray = Array.from(map1.values());
console.log(valueArray);
</script>
</body>
</html>
es6 map数据结构
最新推荐文章于 2023-06-21 15:29:43 发布