Set是ES6中新增的类型,和数组类似,唯一不同在于该类型不会有重复的数据,一般常用来对数组去重****以下几个set常用方法
1. 数组去重 :
- 单一数组的去重。
let set1 = new Set([1, 2, 2, 3, 4, 3, 5]) console.log('distinct 1:', set1)
结果:distinct 1: { 1, 2, 3, 4, 5 }
- 多数组的合并去重
let arr1 = [1, 2, 3, 4] let arr2 = [2, 3, 4, 5, 6] let set2 = new Set([...arr1, ...arr2]) console.log('distinct 2:', set2)
结果 :distinct 2: { 1, 2, 3, 4, 5, 6 }
2. 类型转换
set给数组去重以后得到的结果不是数组结构 , 需要转换成数组 , 方法如下 :
- Set转数组
let set3 = new Set([4, 5, 6]) console.log('set to array 1:',[...set3]) // 解构赋值 console.log('set to array 2:', Array.from(set3))
结果:
set to array 1: [ 4, 5, 6 ] set to array 2: [ 4, 5, 6 ]
- 数组转Set
let set2 = new Set([4,5,6]) console.log('array to set 1:', set2)
let set3 = new Set(new Array(7, 8, 9)) console.log('array to set 2:', set3)
结果:
array to set 1: Set { 4, 5, 6 } array to set 2: Set { 7, 8, 9 }
3. set的操作
- 增删add( ) , delete( )
- 查询是否有某元素has( )
4. 其他特性
- Set的键名和键值是同一个值,它的每一个元素的key和value是相同的
- 在向Set加入值时,Set不会转换数据类型,内部在判断元素是否存在时用的类似于精确等于(===)的方法,“2”和2是不同的,NaN等于其自身。