Set-使用方法及特性

8次阅读

共计 815 个字符,预计需要花费 3 分钟才能阅读完成。

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 等于其自身。
正文完
 0