一、set数据结构 (使用 new来创建一个set集合 通过add方法添加元素 通过size来获取set集合的长度)
{
let list = new Set();
list.add(5);
list.add(7);
console.log('size',list.size);
}
还有另外一种初始化的方式(通过直接把数组传递进去)
{
let arr = [1,2,3,4,5];
let list = new Set(arr);
console.log('size',list.size);
}
set里面的元素不可以重复(可以通过set的这个特性进行数组去重,注意:转化过程中不会进行 数据类型转化)
{
let list = new Set();
list.add(1);
list.add(2);
list.add(1);//不会报错 只是不会生效
console.log('list',list);
let arr=[1,2,3,1,'2'];
let list2=new Set(arr);
console.log('unique',list2);
}
set的一些方法(add ,delete,clear,has)
{
let arr=['add','delete','clear','has'];
let list=new Set(arr);
console.log('has',list.has('add'));//是否包含
console.log('delete',list.delete('add'),list);//清空
list.clear();
console.log('list',list);
}
set的遍历(keys和values返回的都是set里面的值)
{
let arr=['add','delete','clear','has'];
let list=new Set(arr); for(let key of list.keys()){
console.log('keys',key);
} for(let value of list.values()){
console.log('value',value);
} for(let [key,value] of list.entries()){
console.log('entries',key,value);
}
list.forEach(function(item){console.log(item);})
}
WeakSet(里面的元素只能是对象,并且不会检测所添加的对象是否在别处引用,没有size clear 不支持遍历)
{
let weakList=new WeakSet();
let arg={};
weakList.add(arg); // weakList.add(2);
console.log('weakList',weakList);
}
二、Map数据结构(Map是通过key/value进行设置的,所以设置用set方法,获取使用get方法)
{
let map = new Map();
let arr=['123'];
map.set(arr,456);
console.log('map',map,map.get(arr));
}
Map的另外一种定义方式(同时size delete clear方法一样)
{
let map = new Map([['a',123],['b',456]]);
console.log('map args',map);
console.log('size',map.size);
console.log('delete',map.delete('a'),map);
console.log('clear',map.clear(),map);
}
weakMap数据结构(和setMap的特性一致)
{
let weakmap=new WeakMap();
let o={};
weakmap.set(o,123);
console.log(weakmap.get(o));
}