本文内容
Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。
基本使用
- iterator 与Map类似,Set接收一个可选的Iterator对象,所有元素将按照顺序不重复地添加到Set中。传递null或者undefined将返回一个空Set
1 2 3 4 5 6 7 8 9
| const set = new Set(); // 添加元素 set.add(1); // 移除元素 set.delete(1); // 检测元素是否存在 set.has(1); // 清空Set set.clear();
|
数据类型的唯一性判定
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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);
|
输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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迭代
1 2 3 4 5 6 7
| const set = new Set(undefined);
set.add("string").add("string");
for (const v of set.entries()) { console.log(v); }
|
forEach
1 2 3 4 5 6 7
| const set = new Set(undefined);
set.add("string").add("string");
set.forEach(function(value) { console.log(value); });
|
使用场景
Set和数组相互转化
1 2 3
| const array = [1,2]; const set = new Set(array); // 数组转化为set const newArray = [...set]; // set转化为数组
|
去除字符串重复字符
1 2 3 4 5
| const s = 'aabbcc';
const set = new Set(s); const newString = [...set].join(''); console.log(newString); // abc
|
数组去重
1 2 3
| const list = [1,2,3,1,2,3]; const set = new Set(list); console.log([...set]); // [1,2,3]
|
并集
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]
|
交集
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]
|
差集
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去实现就可以省去重复判断之类的操作,可以专注业务逻辑。
