最近才發現這個好用的方法。
簡述
new Set
是 ES6 推出的一種資料型態,如果你不希望「Array 裡出現重複的值」,這個絕對好用。
先來看個簡短的範例,你大概就知道用法了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const obj = { name: 'PeaNu' }
const mySet = new Set()
mySet.add(1) mySet.add(1) mySet.add(3) mySet.add(3) mySet.add(5) mySet.add(6) mySet.add(obj)
console.log(mySet) console.log(mySet.has(3)) console.log(mySet.has(4))
console.log(mySet.delete(obj)) console.log(mySet.delete(7)) console.log(mySet) console.log(mySet.size)
console.log(mySet.entries()) console.log(mySet.keys()) console.log(mySet.values())
|
接下來會示範幾個實際應用。
過濾掉陣列中重複的元素
因為 new 出來的 Set
會是 Object,所以記得用 ...
轉成 Array 就好了。
1 2 3 4
| const array = [1, 1, 3, 4, 5, 6, 6, 3, 4] const mySet = new Set(array) const filterArray = [...mySet] console.log(filterArray)
|
檢查陣列中是否包含某物件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const classroom = new Set() const PeaNu = { id: 1, name: 'PeaNu' } const PPB = { id: 2, name: 'PPB' } const Nick = { id: 3, name: 'Nick' }
classroom.add(PeaNu) classroom.add(PPB) classroom.add(Nick)
if (classroom.has(PeaNu)) { console.log(`${PeaNu.name} is in the classroom`) }
classroom.delete(Nick)
if (!classroom.has(Nick)) { console.log('Can not find Nick') }
console.log(`Now there are ${classroom.size} students`)
|