Set
与Array类似,只是其元素是不能重复的。遍历可用forEach for of
const s1 = new Set([1,2,3,3]) // 初始化 1 2 3
const s = new Set(); // 初始化
s.add(1).add(2).add(1); // 1 2
s.size; // 2
s.has(1) // true
s.delete(3) // false
s.clear()
- 实际使用场景
// 数组去重, 利用Set特性及展开符或者Array.from
const arr = [1,2,3,2,4,3,5]
const newArr = [...new Set(arr)]
const newArr1 = Array.from(new Set(arr))
Map
与对象类似,是键值对集合,但对象的键只能为string或者symbol,如果不是string,也会调用toString()方法转化为string,。Map的“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。
const m = new Map()
const tom = { name : 'tom'}
m.set(tom, 90)
m.get(tom) // 90
m.has(tom) // true
m.delete(tom) // true
m.clear()
Symbol
一个独一无二的值。
const sym = Symbol() // 生成一个独一无二的值
typeof sym // symbol
- 实践
// 实现私有变量
const obj ={
[sym] : 'tt',
say() {
console.log(this[sym])
}
}
// 添加独一无二的对象键值,防止冲突
const obj1 = {
[Symbol('foo')] : 1,
[Symbol('foo')] : 2
}
- 遍历
in Object.keys() Json.stringfy()都会忽略对象键值为symbol的属性
Object.getOwnPropertySymbols()
方法,可以获取指定对象的所有 Symbol 属性名。该方法返回一个数组,成员是当前对象的所有用作属性名的 Symbol 值。