本文主要是介绍ES6:Set()与weakSet(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、Map()
1.1 简介
ES6 提供了 Set 数据结构,它类似于数组,但是值是唯一没有重复的。
我们可以通过 new Set()去创建它。
1.2. Set的创建、设置与获取
<script>const set = new Set();console.log(set.add(1)); //Set { 1 }const arr = [1, 2, 3, 4, 5];console.log(set.add(arr)); //Set { 1, [1, 2, 3, 4, 5] }console.log([...set]); //[1, [1, 2, 3, 4, 5]]</script>
1.3 Set()的一些方法
1.size 返回 Set 结构的成员总数。
2.has 方法返回一个布尔值,表示某个值是否在当前 Set 集合之中。
3.delete 删除一个值,成功返回 true,失败(即该值不在 Set 中)返回 false。
4.clear 清除 Set 集合中的所有成员。
<script>// 创建一个 Setconst mySet = new Set();mySet.add(1);mySet.add("hello");mySet.add({ id: 1 });// 1. 获取Set的大小(成员总数)console.log(mySet.size); // 输出:3// 2. 判断值是否存在console.log(mySet.has(1)); // 输出:trueconsole.log(mySet.has("world")); // 输出:false// 3. 删除一个值console.log(mySet.delete("hello")); // 输出:trueconsole.log(mySet.has("hello")); // 输出:false// 4. 清除所有成员mySet.clear();console.log(mySet.size); // 输出:0</script>
1.4 遍历Set
1.Set.prototype.keys():返回键名的遍历器
2.Set.prototype.values():返回键值的遍历器
3.Set.prototype.entries():返回键值对的遍历器
4.Set.prototype.forEach():使用回调函数遍历每个成员
<script>// 创建一个 Setconst mySet = new Set(["a", "b", "c"]);// 使用 keys() 方法遍历 Setfor (const item of mySet.keys()) {console.log(item);} // a b c// 使用 values() 方法遍历 Setfor (const value of mySet.values()) {console.log(value);} // a b c// 使用 entries() 方法遍历 Setfor (const entry of mySet.entries()) {console.log(entry);} // ["a", "a"] ["b", "b"] ["c", "c"]// 使用 forEach() 方法遍历并处理 Set 中的每个成员mySet.forEach((item) => {console.log(`Processing ${item}`);}); // Processing a Processing b Processing c</script>
1.5 Set()的应用
<script>//数组去重const mySet = new Set([1, 1, 2, 3, 4, 5, 5, 6]);console.log([...mySet]); // [1, 2, 3, 4, 5, 6]//字符串去重console.log([...new Set("ababbc")].join("")); // abc</script>
注意:未展开的数组无法去重,需要先扁平化
<script>const arr = [[1, 2, 3],[2, 5, 6],[2, 8, 9],];console.log(new Set(arr)); //Set(3) { [ 1, 2, 3 ], [ 2, 5, 6 ], [ 2, 8, 9 ] }console.log([...new Set(arr.flat())]); //[ 1, 2, 3, 5, 6, 8, 9 ]</script>
二、WeakSet
2.1 简介
WeakSet 结构与 Set 类似,也是不重复的值的集合。它和Set主要有以下区别:
1.WeakSet 的成员只能是对象和 Symbol 值,而不能是其他类型的值。
2.WeakMap其键值对之间是弱引用关系。对于WeakMap中的键,如果除了WeakMap之外没有任何其他强引用指向该键所在的对象,则垃圾回收器可以在下一次垃圾回收周期中回收这个键所指向的对象,即使WeakMap还持有该键值对。
2.2 基本使用
<script>const a = [[1, 2],[3, 4],];const ws = new WeakSet(a);console.log(ws); //{1, 2}, {3, 4}ws.add(5);//报错</script>
这篇关于ES6:Set()与weakSet()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!