0
点赞
收藏
分享

微信扫一扫

set集合和map集合

伽马星系 2022-02-18 阅读 85

set集合

// 创建set对象
let imgs = new Set();
//添加元素
imgs.add(100);
imgs.add(100);
imgs.add("hello");
imgs.add("hello");
imgs.add("true");
imgs.add(new String("world"));
imgs.add(new String("world"));
// 如果添加相等的元素,则只会保存第一个元素:
console.log(imgs); // {100, 'hello', 'true', {'world'}, {'world'}}
  • for…of遍历集合
// keys()	返回 Set 对象中值的数组。
for(let item of imgs.keys()){
    console.log(item);
}

在这里插入图片描述

// values()	与 keys() 相同
for(let item of imgs.values()){
     console.log(item);
 }

在这里插入图片描述

// entries() 迭代对象中数组的索引值作为 key, 数组元素作为 value
for(let item of imgs.entries()){
    console.log(item);
}

在这里插入图片描述

//数组变集合
var set = new Set([10,20,30,30,50,10,60,50]);
console.log(set); // {10, 20, 30, 50, 60}

//集合变数组 将数据解构展开成数组
var arr = [...set];
console.log(arr); // [10, 20, 30, 50, 60]

map集合

// 创建map对象
let map = new Map();

//添加数据
map.set("张三","打鱼的");
map.set("李四","种地的");
map.set("王五","挖煤的");

console.log(map);

在这里插入图片描述

// 取值
alert(map.get("王五"));

在这里插入图片描述

/* 
 	map遍历     通过for of
*/
for(let [key,value] of map){
    console.log(key,value);
}

在这里插入图片描述

举报

相关推荐

0 条评论