# ES6，新增数据结构Set的用法

ES6 提供了新的数据结构 Set。

let set6 = new Set([1, 2, 2, 3, 4, 3, 5])
console.log('distinct 1:', set6)

distinct 1: Set { 1, 2, 3, 4, 5 }

let arr1 = [1, 2, 3, 4]
let arr2 = [2, 3, 4, 5, 6]
let set7 = new Set([...arr1, ...arr2])
console.log('distinct 2:', set7)

distinct 2: Set { 1, 2, 3, 4, 5, 6 }

1.向Set中添加元素。

let set1 = new Set()
console.log('added:', set1)

added: Set { 1, 2, 3 }

2.从Set中删除元素。

let set1 = new Set()
set1.delete(1)
console.log('deleted:', set1)

deleted: Set { 2, 3 }

3.判断某元素是否存在。

let set1 = new Set()
set1.delete(1)
console.log('has(1):', set1.has(1))
console.log('has(2):', set1.has(2))

has(1): false
has(2): true

4.清除所有元素。

let set1 = new Set()
set1.clear()
console.log('cleared:', set1)

cleared: Set {}

Set和Array互转

1.数组转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 2: Set { 4, 5, 6 }
array to set 3: Set { 7, 8, 9 }

2.Set转数组

let set4 = new Set([4, 5, 6])
console.log('set to array 1:', [...set4])
console.log('set to array 2:', Array.from(set4))

set to array 1: [ 4, 5, 6 ]
set to array 2: [ 4, 5, 6 ]

let set5 = new Set([4, 5, 'hello'])
console.log('iterate useing Set.keys()')
for(let item of set5.keys()) {
console.log(item)
}

console.log('iterate useing Set.values()')
for(let item of set5.values()) {
console.log(item)
}

console.log('iterate useing Set.entries()')
for(let item of set5.entries()) {
console.log(item)
}

iterate useing Set.keys()
4
5
hello
iterate useing Set.values()
4
5
hello
iterate useing Set.entries()
[ 4, 4 ]
[ 5, 5 ]
[ 'hello', 'hello' ]

let set8 = new Set()
console.log('NaN===Nan is true:', set8)
NaN===Nan is true: Set { NaN }