- 基本用法 (增删清)
let s = new Set([1, 2, 3, 4, 2]);
console.log(s) // Set(4) {1, 2, 3, 4}
console.log(s.size) // 4
s.add('new')
console.log(s) // Set(5) {1, 2, 3, 4,'new'}
s.delete(3)
console.log(s) // Set(4) {1, 2, 4,'new'}
s.clear()
console.log(s) // Set() {}
2.可遍历 (key和value相等)
let s1 = new Set([1, 2, 3, 4]); //可遍历 key和value相等
console.log('s1', s1)
for (const item of s1.keys()) {
console.log('item', item) //1,2,3,4
}
for (const item of s1.values()) {
console.log('item', item) //1,2,3,4
}
for (const item of s1.entries()) {
console.log('item', item) //[1,1] [2,2] [3,3] [4,4]
}
应用
1.去重
let a1 = [1, 2, 3, 4, 5];
let a2 = [3, 4, 5, 6, 7];
// 去重
let s1 = new Set([...a1, ...a2]); //通过set元素不可重复 实现去重
s1 = Array.from(s1) //通过Array.fromset转array
console.log(s1) // [1, 2, 3, 4, 5, 6, 7]
网友评论