1. Set基本用法
Set类似于数组,但是其内部的成员的值都是唯一的,没有重复的值。
Set本身是一个构造函数,用来生成Set数据结构。
// 例一
const s = new Set([1,2,3,3,2,1]);
console.log(...s) //1 2 3
// 例二
const arr = [1,2,3,3,2,5]
const s = [...new Set(arr)]
console.log(s) // [1,2,3,5]
// 例三
const str = 'aabbcd'
const s = [...new Set(str)].join('')
console.log(s) // 'abcd'
// 例四
const s = new Set([1,2,3,3,2,1]);
console.log(s.size) // 3
2.Set实例的方法和属性
属性:
Set.prototype.constructor: 构造函数,默认就是Set函数。
Set.prototype.size: 返回Set实例的成员总数。
方法:
操作方法
add(value): 添加某值,返回Set结构本身。
delete(value): 删除某值, 返回布尔值。
has(value): 检测Set的成员是否有这个值,返回布尔值。
clear(value): 清除所有成员,不返回值。
遍历方法
keys():返回键名的遍历器
values():返回键值的遍历器
entries():返回键值对的遍历器
forEach():使用回调函数遍历每个成员
操作方法例子:
const s = new Set();
s.add(1) // 1
s.add(2) // 1 2
s.add(2) // 1 2
s.has(2) // true
s.delete(1) // true
s.has(1) // false
遍历方法例子
const arr = ['red','blue','yellow','skyblue']
const s = new Set(arr);
for(let i of s.keys()){
console.log(i)
}
// red
// blue
// yellow
// skyblue
for(let i of s.values()){
console.log(i)
}
// red
// blue
// yellow
// skyblue
for(let i of s.entries()){
console.log(i)
}
// ['red','red']
// ['blue','blue']
// ['yellow','yellow']
// ['skyblue','skyblue']
s.forEach((key,value) => console.log(`${key}: ${value}`))
// red: red
// blue: blue
// yellow: yellow
// skyblue: skyblue