在 ES6 中,集合(Set)是一个全新的数据结构,它允许存储不重复的值。Set 可以存储任意类型的值,包括原始类型和对象引用。本文将详细介绍 ES6 中集合的特性和用法,并提供示例代码以供参考。
创建 Set
使用 Set 的静态方法可以创建一个空的 Set:
const set = new Set(); console.log(set); // Set {}
使用数组初始化 Set,数组中的重复值将被自动去重:
const set = new Set([1, 2, 3, 2, 1]); console.log(set); // Set {1, 2, 3}
Set 中的值可以是任意类型的,包括引用类型:
const set = new Set([{ id: 1 }, { id: 2 }, { id: 1 }]); console.log(set); // Set {{ id: 1 }, { id: 2 }}
Set 的常用方法
add 和 has
使用 add 方法可以向 Set 中添加一个值:
const set = new Set(); set.add(1); set.add(2); console.log(set); // Set {1, 2}
使用 has 方法可以判断 Set 中是否包含某个值:
const set = new Set([1, 2, 3]); console.log(set.has(2)); // true console.log(set.has(4)); // false
delete 和 clear
使用 delete 方法可以从 Set 中删除一个值:
const set = new Set([1, 2, 3]); set.delete(2); console.log(set); // Set {1, 3}
使用 clear 方法可以清空 Set 中的所有值:
const set = new Set([1, 2, 3]); set.clear(); console.log(set); // Set {}
size 属性
Set 中的元素个数可以通过 size 属性获取:
const set = new Set([1, 2, 3]); console.log(set.size); // 3
遍历 Set
Set 可以使用 for...of 循环进行遍历:
const set = new Set([1, 2, 3]); for (const value of set) { console.log(value); } // 1 // 2 // 3
Set 还提供了 forEach 方法用于遍历:
const set = new Set([1, 2, 3]); set.forEach(value => console.log(value)); // 1 // 2 // 3
Set 的应用
数组去重
Set 可以方便地实现数组去重:
const arr = [1, 2, 3, 2, 1]; const set = new Set(arr); console.log([...set]); // [1, 2, 3]
判断两个数组是否相等
使用 Set 可以方便地判断两个数组是否相等:
const arr1 = [1, 2, 3]; const arr2 = [3, 2, 1]; console.log(new Set(arr1).equals(new Set(arr2))); // true
求两个数组的交集、并集、差集
使用 Set 可以方便地求两个数组的交集、并集、差集:
-- -------------------- ---- ------- ----- ---- - --- -- --- ----- ---- - --- -- --- ----- ---- - --- ---------- ----- ---- - --- ---------- -- -- ---------------------------------- -- ------------------ -- --- -- -- ------------------- ------------- ------------ -- --- -- -- -- -- -- -- ---------------------------------- -- ------------------- -- --- --展开代码
总结
ES6 中的集合(Set)是一种强大的数据结构,它可以帮助我们处理众多的数据问题。本文介绍了 Set 的特点和常用方法,并提供了多个示例代码以供参考。把握好 Set 的使用方式,能够提高我们的开发效率,节省宝贵的时间和精力。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/65b76e40add4f0e0ffffcd0a