es6 Set数据结构 学习笔记

 

Set是ES6提供的一种新的数据结构,它类似于数组,但是成员都是独一无二的,没有重复的值。

Set函数本身是一个构造函数,用来生成Set数据结构。

Set函数接受一个具有Iterable接口的数据结构作为参数,用来初始化。

//情景1:不传递参数
let set1=new Set();

//情景2:接受一个数组作为参数
let set2=new Set([1,2,3]);

//情景3:接受一个map作为参数
let map=new Map([['num',1]]);
let set3=new Set(map);

Set数据结构与数组的转换

1、Array.from(Set)

2、[...Set]

Set实例的属性

1 、Set.prototype.constructor 构造函数 即Set函数

2、 Set.prototype.size 返回实例成员的总数

Set实例的操作方法与遍历方法

1、add(value) 添加某个值,返回Set结构本身

向Set加入值的时候,不会发生类型转换。

Set内部判断两个值是否相同,使用的算法叫做 “Same-value-zero equality”,类似于‘===’。区别在于在Set内部,null等于null。

var set=new Set()
set.add(5).add('5') //set {5,'5'}
set.add(null).add(null) //set {null}

2、 delete(value) 删除某个值,返回布尔值,false 表示删除失败,true表示删除成功

3、 has(value)  返回一个布尔值,表示该值是否为Set的成员。

4、 clear() 清除所有成员,没有返回值。

5、 keys() 返回键名的遍历器

6、 values() 返回键值的遍历器

7 、entries() 返回键值对的遍历器

8、 forEach() 使用回调函数遍历每个成员

9 、for...of... 遍历的for ..of...方法

Set的过滤

可以间接通过数组的filter方法实现Set数据结构的过滤

let set = new Set( [ 1, 3, 4, 5, 7, 8 ] )
set = new Set( [ ...set ].filter( item => item % 2 > 0 ) ) //set {1,3,4,5}

Set的排序

间接使用数组的sort方法实现Set数据结构的排序

let set = new Set( [ 1, 9, 11, 4, 5, 7, 8 ] )
set = new Set( [ ...set ].sort( ( a, b ) => a - b ) ) // set {1,4,5,7,8,9,11}

 

猜你喜欢

转载自blog.csdn.net/qq_35437531/article/details/82800928
今日推荐