ES6之Set

198 阅读2分钟

每天做个总结吧,坚持就是胜利!

    /**
        @date 2021-06-08
        @description ES6之Set
    */

壹(序)

ES6新增了一种数据结构Set,和数组类似,但是里面的值是不重复的,使用Set构造函数生成,自带Iterator接口。

贰(使用)

使用Set构造函数进行声明,传一个带有Iterator接口的数据结构如Array,String等,会自动过滤重复的值:

let set = new Set('abcddcba');
console.log(set); // Set(4) {"a", "b", "c", "d"}

let set = new Set([1, 2, 3, 1, 2, 3]);
console.log(set); // Set(3) {1, 2, 3}

叁(内置属性及方法)

共用代码:

let set = new Set([1, 2, 3, 1, 2, 3]);
  1. size-获取Set中值的数量;
set.size; // 3
  1. add-新增一个值(返回Set本身);
set.add(4); 
console.log(set); // Set(3) {1, 2, 3, 4}
  1. has-检查Set中是否含有某个值;
set.has(5); // false
set.has(1); // true
  1. delete-删除一个值(返回是否删除成功);
set.delete(2); // true
set.delete(2); // false
  1. clear-清空Set(不返回值);
set.clear();
console.log(set); // Set(0) {}
  1. values, keys, entries-返回一个Iterator对象
// values()与keys()的行为完全一致,因为Set对象中键名与键值是相同的;
// entries()返回的遍历器包含键名与键值,两者完全相同;
// 由于返回的是一个Iterator对象,所以可以直接使用for...of进行遍历操作;
for(const item of set.values()){
    console.log(item); // 1, 2, 3
}
for(const item of set.keys()){
    console.log(item); // 1, 2, 3
}
for(const item of set.entries()){
    console.log(item); // [1, 1], [2, 2], [3, 3]
}
for(const item of set){
    console.log(item); // 1, 2, 3
}
  1. forEach-遍历Set对象,与ArrayforEach方法类似;
set.forEach(((value, key, set) => {
    console.log(value, key, set)
}))
/** 
    1 1 Set(3) {1, 2, 3}
    2 2 Set(3) {1, 2, 3}
    3 3 Set(3) {1, 2, 3}
*/

肆(应用)

  1. 数组去重;
let arr = [1, 2, 3, 1, 2, 3];
arr = Array.from(new Set(arr)); // [1, 2, 3]
  1. 字符串去重;
let str = 'abcdddaaf';
str = [...new Set(str)].join(''); // "abcdf"
  1. 无法直接改变Set对象中的值,只能通过变通方法构建一个新的Set对象;
// 1. 使用Array.from
let set = new Set([1, 2, 3]);
set = new Set(Array.from(set, (val) => val + 1)); // Set(3) {2, 3, 4}
// 2. 使用Array.map
set = new Set([...set].map(item => item + 1)); // Set(3) {3, 4, 5}

伍(引申)

Set相对应的是一个叫做WeakSet的数据结构,WeakSet与Set一样,里面的值是不重复的;

SetWeakSet的区别:

  1. WeakSet只能存储引用数据类型
const ws = new WeakSet([1]); // Uncaught TypeError: Invalid value used in weak set
const ws = new WeakSet([{}]); // WeakSet {{…}}
  1. WeakSet中的对象都是弱引用,即垃圾回收机制不会考虑某个对象在WeakSet中的引用,只要其他地方没有再用到WeakSet里面的对象,那么就会被垃圾回收机制清理;
  2. WeakSet相比于Set,内置属性与方法较少,没有size属性,forEach方法,values方法等;
const ws = new WeakSet();
const obj = {}
console.log(ws.size); // undefined
// add
ws.add(obj); // WeakSet {{…}}
// has
ws.has(obj); // true
// delete
ws.delete(obj); // true