ES6的Set类型
16lz
2021-04-12
本文内容
Set的基本使用
- 常用用法
Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。
基本使用
new Set([iterator])
- iterator
与Map类似,Set接收一个可选的Iterator对象,所有元素将按照顺序不重复地添加到Set中。传递null或者undefined将返回一个空Set
const set = new Set();// 添加元素set.add(1);// 移除元素set.delete(1);// 检测元素是否存在set.has(1);// 清空Setset.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); // 数组转化为setconst 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去实现就可以省去重复判断之类的操作,可以专注业务逻辑。
更多相关文章
- DOM 元素的增删改查操作 ----0406
- c++ vector模拟实现
- CSS常用布局类型
- 关于scrollHeight、scrollTop、clientHeight的总结
- Dom元素增加删除,修改,查找
- JS中的值传递,模板字面量,数组、对象、传参解构,访问器属性
- CSS选择器
- python列表
- JavaScript:留言板添加字数实时统计与禁止超出功能,部分字符串和