js-数组-set结构-1.1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caishu1995/article/details/88974187

    今天发现ES6提供了set这种新的数据结构,类似数组,但其中的每个成员都会是唯一的。但这里需要注意的是,唯一标准是===,这说明如果类型不同,就算值一样,他也会认为是两个成员哦。

    那么我们就能通过他的这个特性,做一些操作了,比如去重啊。。。等。

    我们先来看看,如何定义一个set结构。

const numberSet = new Set(numberArray);

    因为他类似数组,那就可以一个个加

numberSet.add(6);

    也可以将一个数组一起灌进来

const numberArray = [1, 2, 3, 2, 4];
const numberSet = new Set(numberArray);

    如何使用set结构呢?一般是转成数组,然后通过数组方式使用。

const numberSetToArray = [...numberSet];

    增删改查,除了查看和新增,当然结构中不能少了删除,和判断是否存在。这个跟数组就一样了。

numberSet.delete(2);//删除2

numberSet.clear();//清空所有
console.log(numberSet.has(4)); //true         //是否存在
console.log(numberSet.has(5)); //false

猜你喜欢

转载自blog.csdn.net/caishu1995/article/details/88974187