ES6(八) map的结构

map 结构

/*数据结构map*/
/*键值对:与对象不同的是键和值可以使任意类型*/
const map1 = new Map();
const key1 = "some String";
const key2 = {};
const key3 = function() {};

//为key设置value值
map1.set(key1, "1里面的值");
map1.set(key2, "2里面的值");
map1.set(key3, "3里面的值");

//根据key获取当前的value值

console.log(map1.get(key1));
console.log(map1.get(key2));
console.log(map1.get(key3));

//获取对应的map数量
console.log(map1.size);
// for of 用来循环map的
for (let [key, value] of map1) {
    console.log(`${key}=${value}`);

}
//只获取key值
for (let key of map1.keys()) { //里面必须是keys()
    console.log(key);
}

//只获取值
for (let value of map1.values()) { //里面必须是keys()
    console.log(value);
}
//foreach
map1.forEach((value, key) => {
    console.log(`${key}=${value}`);
})
//将map1转化为正常的数组
const arr1 = Array.from(map1);
const arr2 = Array.from(map1.values());
console.log(arr1);
console.log(arr2);
//将map1中的value值转换为数组

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录