Set/WeakSet
新的数据结构Set
代码的形式体现。
声明方式
常用方法
应用场景
WeakSet
const s2 = new Set([1, 2, 2, 3]);
console.log(s2);
s2.add(4);
s2.add(5).add(6);
console.log(s2);
s2.delete(2);
console.log(s2.delete(1), s2);
console.log(s2.has(3), s2.has(7));
console.log(s2.size);
s2.clear();
console.log(s2);
s2.add(1).add(2).add(3).add(4);
s2.forEach(val => {
console.log(val)
})
for (const val of s2) {
console.log(val);
}
for (const k of s2.keys()) {
console.log(k);
}
for (const v of s2.values()) {
console.log(v);
}
for (const entry of s2.entries()) {
console.log(entry[0], entry[1], entry);
}
const s3 = new Set([1, 2, 3, 3, 2, 1]);
console.log(s3, s3.size);
const s4 = new Set([...[1, 2, 3], ...[1, 2, 3, 4]]);
console.log(s4, s4.size, [...s4]);
console.log(Array.from(s4));
const a1 = [1, 2, 3, 3, , 4];
const a2 = [2, 3, 5];
const s5 = new Set(a1);
const s6 = new Set(a2);
const res = new Set(a1.filter(val => s6.has(val)));
console.log([...res]);
const res2 = new Set(a1.filter(val => !s6.has(val)));
const res3 = new Set(a2.filter(val => !s5.has(val)));
console.log([...res2, ...res3]);
const ws1 = new WeakSet();
let obj1 = { name: "战三" };
const obj2 = { name: "lisi" };
ws1.add(obj1).add(obj2);
console.log(ws1.has(obj1));
|