类型 | 用途 | 属性 | 方法 | 遍历 |
---|---|---|---|---|
Set | 值不重复 | size | add delete has clear | yes |
WeakSet | 值不重复,且为对象,且垃圾回收不考虑此引用 | no | add delete has | no |
Map | 键可以为对象 | size | [set get]delete has clear | yes |
WeakMap | 键为对象,且垃圾回收不考虑此引用 | no | [set get] delete has | no |
weak 表示弱引用 垃圾回收不考虑此引用,不可遍历,没有大小(WeakMap)键或(WeakSet)值需要是对象
let p= new Set([1,1])//1
const set = new Set([1, 2, 3, 4, 4]);
const set = new Set(document.querySelectorAll('div'));
let set = new Set();
let a = NaN;
let b = NaN;
set.add(a);
set.add(b);
set // Set {NaN}
NaN===NaN //false
[...new Set(array)]
[...new Set('ababbc')].join('')
let s= new Set([1])
s.add(2)
s.size // 2
s.has(1) // true
s.delete(2);
let set = new Set(['red', 'green', 'blue']);
for (let item of set.keys()) {
console.log(item);
}
// red green blue
for (let item of set.entries()) {
console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
const b = [3, 4];
const ws = new WeakSet(b);
// Uncaught TypeError: Invalid value used in weak set(…)
const map = new Map([
['name', 'a'],
['title', 'b']
]);
{true:1,'true':2}//{'true':2}
let map = new Map();
map.set(true, 1);
map.set('true', 2);
map.get(true) // 1
map.get('true') // 2
let map= new Map()
map.set(1,1);
map.get(1);//1
map.has(1);//true 是否有某个键
map.size//1
map.delete(1)//true 成功true 失败false
map.clear()//除所有成员,没有返回值
for (let key of map.keys()) {
console.log(key);
}
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
或者解构赋值
for (let [key, value] of map.entries()) {
console.log(key, value);
}
或者默认遍历器
for (let [key, value] of map) {
console.log(key, value);
}
const myMap = new Map()
.set(true, 7)
.set({foo: 3}, ['abc']);
[...myMap]
// [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]
//一旦这个 DOM 节点删除,该状态就会自动消失,不存在内存泄漏风险。
let myElement = document.getElementById('logo');
let myWeakmap = new WeakMap();
myWeakmap.set(myElement, {timesClicked: 0});
myElement.addEventListener('click', function() {
let logoData = myWeakmap.get(myElement);
logoData.timesClicked++;
}, false);
const _counter = new WeakMap();
class Countdown {
constructor(counter, action) {
//内部属性_counter,是实例的弱引用,所以如果删除实例,它们也就随之消失,不会造成内存泄漏
_counter.set(this, counter);
}
dec() {
let counter = _counter.get(this);
if (counter < 1) return;
counter--;
_counter.set(this, counter);
}
}