Set

  • set数据结构类似于数组,但是里面不能有重复的值
  • 注意:Set({a:1})这样使用是错误的,括号里面不能直接放对象,但可以通过add()方法进行添加
  • 用法:
let a = new Set(['a','b']);
console.log(a);//{"a", "b"}

set数据结构的几种方法

  • add() – 添加一项
    该方法可以链式调用
let a = new Set(['a','b']);
a.add(1);
//a.add(1,2);//这样写也只会添加1进去
console.log(a);//{"a", "b", 1}
  • delete() – 删除一项
let a = new Set(['a','b']);
a.delete('a');
console.log(a);//{'b'}
  • has() – 判断里面有没有某个值
let a = new Set(['a','b']);
a.has('a');//true
  • size – 个数
let a = new Set(['a','b']);
console.log(a.size);//2
  • clear() – 清空
let a = new Set(['a','b']);
a.clear();
console.log(a);//{}

set数据结构的遍历

Set数据结构的key值和value值是一样的,遍历的时候默认遍历的是value

let setArr = new Set(['a','b','c','d']);

for(let item of setArr.keys()){
   
    console.log(item);
}
console.log('---------------------------');

for(let item of setArr.values()){
   
    console.log(item);
}
console.log('---------------------------');

for(let item of setArr.entries()){
   
    console.log(item);
}

console.log('---------------------------');

for(let [k,v] of setArr.entries()){
   
    console.log(k,v);
}

最好直接使用forEach进行遍历

let setArr = new Set(['a','b','c','d']);

setArr.forEach((value,index) =>{
   
    console.log(value, index);
});

set的一些用处

  • 可以通过扩展运算符…来实现数组去重
let arr = [1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4,4];

let newArr = [...new Set(arr)];

console.log(newArr);//[1, 2, 3, 4, 5, 6, 7]
  • 通过…转化为数组后使用数组map方法
let set = new Set([1,2,3]);
        
set = new Set([...set].map(val=>val*2));

console.log(set);//{2, 4, 6}

WeakSet()

WeakSet()与Set基本一样,WeakSet()里面一般用来放对象
WeakSet()没有size,也没有clear()

Map

Map类似与json,但map的健(key)可以是任意类型

  • 用法:
let map = new Map();

Map的一些方法

与set一样有delete、has、clear三种方法,用法也是一样。Map还有set,get方法

  • set&get
let map = new Map();
        
let json = {
   
    a:1,
    b:2
};

map.set('a','aaa'); //正常

map.set(json, 'aaa');

map.set('aaa', json);

console.log(map.get(json));
console.log(map.get('aaa'));

  • 对map进行遍历
let map = new Map();
        
let json = {
   
    a:1,
    b:2
};

map.set('a','aaa'); //正常
map.set(json, 'aaa');
map.set('aaa', json);

//循环
for(let [key,value] of map){
   
    console.log(key,value);
}

WeakMap()

WeakMap()的key只能是对象