這里貼一段MDN的描述:
Set對象是值的集合,你可以按照插入的順序迭代它的元素。 Set中的元素只會(huì)出現(xiàn)一次,即 Set 中的元素是唯一的。
Set 本身是一種構(gòu)造函數(shù),用來生成 Set 數(shù)據(jù)結(jié)構(gòu)。
看下例子:
const s = new Set();
[1, 2, 3, 4, 3, 2, 1, "1"].forEach(x => s.add(x))
// 通過for of遍歷
for (let i of s) {
console.log(i) // 1 2 3 4 "1"
}
// 利用元素唯一性實(shí)現(xiàn)數(shù)組去重
let arr = [1, 2, 3, 2, 1, 1]
[... new Set(arr)] // [1, 2, 3]
需要注意的是,Set在加入值的時(shí)候,不會(huì)發(fā)生類型轉(zhuǎn)換,所以1和“1”被認(rèn)為是不同的值,類似于使用===來匹配。不過需要注意NaN:NaN === NaN => false。
Set實(shí)例有下面這些方法:
- size:內(nèi)部元素?cái)?shù)量
- add:添加
- delete:刪除
- has:是否存在?返回true和false
- clear:清空集合
let set = new Set()
set.add(1).add(2).add(1)
set.has(1) // true
set.has(3) // false
set.delete(1)
set.has(1) // false
使用Array.from把Set轉(zhuǎn)成數(shù)組,或者使用展開運(yùn)算符:
const items = new Set([1, 2, 3, 2])
const array = Array.from(items)
console.log(array) // [1, 2, 3]
// 或
const arr = [...items]
console.log(arr) // [1, 2, 3]
既然是集合,那么Set就具有可便利性,出了for of,還有實(shí)例對象帶有的方法:
- keys:返回一個(gè)包含集合中所有鍵的迭代器
- values: 返回一個(gè)包含集合中所有值得迭代器
- entries:返回一個(gè)包含Set對象中所有元素得鍵值對迭代器
- forEach:沒有返回值,作用跟數(shù)組forEach相似
let set = new Set([1, 2, 3])
console.log(set.keys()) // SetIterator {1, 2, 3}
console.log(set.values()) // SetIterator {1, 2, 3}
console.log(set.entries()) // SetIterator {1, 2, 3}
for (let item of set.keys()) {
console.log(item);
} // 1 2 3
for (let item of set.entries()) {
console.log(item);
} // [1, 1] [2, 2] [3, 3]
set.forEach((value, key) => {
console.log(key + ' : ' + value)
}) // 1 : 1 2 : 2 3 : 3
console.log([...set]) // [1, 2, 3]
Set跟數(shù)組作用類似,不過是無序的,可以使用Set元素的唯一性輕松實(shí)現(xiàn)交集、并集、差集:
let set1 = new Set([1, 2, 3])
let set2 = new Set([4, 3, 2])
let intersect = new Set([...set1].filter(value => set2.has(value)))
let union = new Set([...set1, ...set2])
let difference = new Set([...set1].filter(value => !set2.has(value)))
console.log(intersect) // Set {2, 3}
console.log(union) // Set {1, 2, 3, 4}
console.log(difference) // Set {1}