乐趣区

ES6的Set类型

本文内容

  • Set 的基本使用
  • 常用用法

Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。

基本使用

new Set([iterator])
  • iterator <Iterator> 与 Map 类似,Set 接收一个可选的 Iterator 对象,所有元素将按照顺序不重复地添加到 Set 中。传递 null 或者 undefined 将返回一个空 Set
const set = new Set();
// 添加元素
set.add(1);
// 移除元素
set.delete(1);
// 检测元素是否存在
set.has(1);
// 清空 Set
set.clear();

数据类型的唯一性判定

const set = new Set(undefined);

set.
    add("string").add("string").
    add(1).add(1).
    add(true).add(true).
    add(null).add(null).
    add(undefined).add(undefined)
    .add(NaN).add(NaN)
    .add({}).add({})
    .add([]).add([])
    .add(function () {}).add(function () {});

console.log(set);

输出如下:

Set {
  'string',
  1,
  true,
  null,
  undefined,
  NaN,
  {},
  {},
  [],
  [],
  [Function],
  [Function]
}

结论

  • string/number/boolean/null/undefined/NaN 是使用值判重

    • NaN!==NaN,但是 Set 也只会存一份,所以值判定应该不完全是用 === 做的
  • object/array/function 等 object 类型使用引用判重

Set 的迭代

for…of

由于 Set 实现了 Symol.iteator 方法,所以可以使用 for…of 迭代

const set = new Set(undefined);

set.add("string").add("string");

for (const v of set.entries()) {console.log(v);
}

forEach

const set = new Set(undefined);

set.add("string").add("string");

set.forEach(function(value) {console.log(value);
});

使用场景

Set 和数组相互转化

const array = [1,2];
const set = new Set(array); // 数组转化为 set
const newArray = [...set]; // set 转化为数组 

去除字符串重复字符

const s = 'aabbcc';

const set = new Set(s);
const newString = [...set].join('');
console.log(newString); // abc

数组去重

const list = [1,2,3,1,2,3];
const set = new Set(list);
console.log([...set]); // [1,2,3]

并集

const set = new Set([1,2,3]);
const set2 = new Set([1,2,3,4]);
const set3 = new Set([...set], [...set2]); // [1, 2, 3]

交集

const set = new Set([1,2,3]);
const set2 = new Set([1,2,3,4]);
const set3 = new Set([...set].filter(item => set2.has(item))); // [1, 2, 3]

差集

const set = new Set([1,2,3]);
const set2 = new Set([1,2,3,4]);
const set3 = new Set([...set2].filter(item => !set.has(item))); // [4], 注意 set2 和 set 的顺序 

总结

在需要唯一性的场景中,Set 使用起来比数组要方便许多,比如添加标签,这个肯定是不重复的,用 Set 去实现就可以省去重复判断之类的操作,可以专注业务逻辑。


更多原创文章,尽在每天进步一点点

退出移动版