在 ES6 中,Set 是一种新的数据结构,它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 对象主要用于去重和数组的操作,它是一种非常实用的集合类型。
Set 对象的应用场景
去重
Set 对象最常见的用途就是去重。由于 Set 对象成员的值都是唯一的,因此可以方便地去除数组中的重复元素。
const arr = [1, 2, 3, 2, 1]; const set = new Set(arr); console.log([...set]); // [1, 2, 3]
数组的操作
Set 对象还可以用来进行数组的操作,例如求交集、并集、差集等。
求交集
const set1 = new Set([1, 2, 3]); const set2 = new Set([2, 3, 4]); const intersection = new Set([...set1].filter(x => set2.has(x))); console.log([...intersection]); // [2, 3]
求并集
const set1 = new Set([1, 2, 3]); const set2 = new Set([2, 3, 4]); const union = new Set([...set1, ...set2]); console.log([...union]); // [1, 2, 3, 4]
求差集
const set1 = new Set([1, 2, 3]); const set2 = new Set([2, 3, 4]); const difference = new Set([...set1].filter(x => !set2.has(x))); console.log([...difference]); // [1]
Set 对象的注意事项
Set 对象的成员必须是唯一的
Set 对象的成员必须是唯一的,如果添加重复元素,Set 对象将自动去除重复的元素。
const set = new Set([1, 2, 3, 2, 1]); console.log([...set]); // [1, 2, 3]
Set 对象的成员可以是任意类型
Set 对象的成员可以是任意类型,包括基本类型和引用类型。
const set = new Set([{name: '张三'}, {name: '李四'}, {name: '张三'}]); console.log([...set]); // [{name: '张三'}, {name: '李四'}]
Set 对象的 size 属性可以获取成员数量
Set 对象的 size 属性可以获取成员数量。
const set = new Set([1, 2, 3]); console.log(set.size); // 3
Set 对象的操作方法
Set 对象有很多操作方法,包括 add、delete、has、clear 等。
- add 方法:添加成员
- delete 方法:删除成员
- has 方法:判断成员是否存在
- clear 方法:清空所有成员
const set = new Set([1, 2, 3]); set.add(4); set.delete(3); console.log(set.has(2)); // true set.clear(); console.log(set.size); // 0
总结
Set 对象是一种非常实用的集合类型,它有很多应用场景,例如去重和数组的操作。在使用 Set 对象时需要注意,其成员必须是唯一的,成员可以是任意类型,而且 Set 对象有很多操作方法,可以方便地进行集合操作。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/65f7ff5ed10417a22236ef4f