本文内容
Set的基本使用 常用用法Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。
输出如下:
Set { 'string', 1, true, null, undefined, NaN, {}, {}, [], [], [Function], [Function] }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去实现就可以省去重复判断之类的操作,可以专注业务逻辑。
更多原创文章,尽在每天进步一点点