javascript - 关于 Set对象的学习

227 阅读1分钟

关于Set对象的一些方法,自己本身也没有做过专门的研究汇总,所以,只是知道它是数组去重的好选择,自己平时在项目中也没有用过这个方法...

趁着闲暇,搞一下,万一以后有用,也可以拿来即用!

专业参考文档:developer.mozilla.org/zh-CN/docs/…

1、数组快速去重经典例子

  • ES6提供的新的数据结构:Set -> 它类似于数组,但是它的成员的值都是唯一的,没有重复的值。
const array = [33, 44, 66, 23, 23, 23, 33, 66, 0];
const arr2 = [...new Set(array)];
console.log(arr2);  //  [33, 44, 66, 23, 0]
  • Array.from():从一个类数组或者可迭代的对象中创建一个新的,浅拷贝的数组实例。
const set = new Set([33, 44, 55, 66, 33]);
const transformSetToArr = Array.from(set);
console.log(set);  // Set(4) {33, 44, 55, 66}
console.log(transformSetToArr);  // [33, 44, 55, 66]

2、Set.has()

const set1 = new Set([1, 3, 4, 5]);
console.log(set1.has(4));   // true
console.log(set1.has('4'));   // false

3、Set.add()

const set2 = new Set();
console.log(set2);  // Set(0) {}
set2.add('addValue');
console.log(set2);  // Set(1) {"addValue"}

4、Set.forEach()

const set4 = new Set([22, 33, 44, 55]);
const setForEach = set4.forEach((ele) => {
    console.log(ele); // 22.33.44,55
});

5、Set.clear()

const setClear = new Set([2, 4, 5, 6, 7]).clear();
console.log(setClear); // undefined

6、Set.delete()

const sourceSet = new Set([22, 33, 44, 55]);
const setDelete = sourceSet.delete(55);
console.log(sourceSet); // Set(3) {22, 33, 44}
console.log(sourceSet.has(55)); // false
console.log(setDelete); // true (!!!竟然返回个TRUE)