一、set
1.set数据结构:类似数组,但是里面不能有重复值
2.set语法, new Set([])
let set=new Set([1,2,1]);
console.log(set);// {1, 2}
3.set 方法
// add() 增加,返回增加后的set
console.log(set.add(3)); // {1, 2,3}
// delete() 删除,返回true或false
console.log(set.delete(2));// true
// has() 判断是否存在某一项,返回true或false
console.log(set.has(1));//true
// clear() 清空
set.clear();
console.log(set);//{}
4.set 属性
// size 查看长度
console.log(set.size);//2
5.set循环
// for of : key,value相等
let set=new Set([1,2,3]);
for(let item of set){//默认是values
console.log(item);// 1 2 3
}
for(let item of set.keys()){
console.log(item);// 1 2 3
}
for(let item of set.values()){
console.log(item);// 1 2 3
}
for(let item of set.entries()){
console.log(item);// [1, 1] [2, 2] [3, 3]
}
set.forEach((value,index)=>{
console.log(value,index);//1 1,2 2,3 3
})
6.set 用法
// 1.数组去重
let arr=[1,2,3,3,1,2,3,1,2];
let set=new Set(arr);
let newArr=[...set]; // set 数据结构变成数组
console.log(newArr);//[1, 2, 3]
// 2.set 利用数组的方法
let set=new Set([1,2,3]);
let arr=[...set];
arr=arr.map((val)=>{
return val*2;
});
set=new Set(arr);//{2, 4, 6}
7. set 注意
// set里面只能是数组
let set=new Set({a:1});
console.log(set);// error:#<Object> is not iterable
// 可以通过add()方法增加
let set=new Set();
let json={
a:1,
b:2
};
let json1={
a:1,
b:3
};
set.add(json);
set.add(json1);
console.log(set);
set.forEach((item)=>{
console.log(item);//{a: 1, b: 2} ,{a: 1, b: 3}
})
二、WeakSet() 存储json,但是初始不可以增加,只能用add增加 ,没有size属性,clear()方法
// 但是初始不可以增加=new WeakSet({})
let set=new WeakSet({
a:1,
b:2
}); //Uncaught TypeError: #<Object> is not iterable
// 只能用add增加 ,没有size属性
let set=new WeakSet();
set.add({a:1})
console.log(set);
console.log(set.size); //undefined
三、Map
Map:类似json,但是json的key 只能是字符串
map的key 可以是任意类型
1.Map语法
// 不可以直接增加{}
let map=new Map({a:1}); //error:#<Object> is not iterable
console.log(map);
// 通过set设置值
let map=new Map();
map.set('a','asd');
console.log(map);//{"a" => "asd"}
2.map 方法
let map=new Map();
let json={a:1};
// set(key,value) 设置值 ,返回设置后的set值
console.log(map.set('a','asd'));//{"a" => "asd"}
console.log(map.set(json,'aaa'));//{"a" => "asd", {…} => "aaa"}
// get(key)获取值
console.log(map.get(json));//aaa
// delete(key) 删除一项,返回true或false
console.log(map.delete(json));//true
// has(key) 判断有没有,返回true或false
console.log(map.has(json));//false
// clear() 清空,无返回值
console.log(map.clear());//undefined
console.log(map);//{}
3.map 循环
for(let [key,value] of map){}//默认 entries()
for(let key of map.keys()){}
for(let value of map.values()){}
for(let [key,value] of map.entries){}
map.forEach((value,index)=>{});
四、WeakMap():key只能是对象
let map=new WeakMap();
let json={a:1};
map.set(json,1);
map.set('a',1);//Uncaught TypeError: Invalid value used as weak map key
console.log(map);
五、总结:
Set里面是数组,不重复,
Map 对json的增强,key可以是任意类型