ES6——Map、Set

2024-06-18  本文已影响0人  LcoderQ

Set和WeakSet

Set的使用

//通过new关键字创建
const set1 = new Set();
set1.add(1)
set1.add(2)
set1.add(2)
set1.add({name:13})
console.log(set1);  //Set(3) { 1, 2, { name: 13 } }

//根据数组创建set对象
const set2 = new Set([1,2,3,4,5,5])
console.log(set2);  //Set(5) { 1, 2, 3, 4, 5 }

//将set转变为数组
const newArray1 = [...set2]
console.log(newArray1);
const newArray2 = Array.from(set2)
console.log(newArray2);

Set的常见属性和方法

method:

WeakSet的使用

const wset = new WeakSet()
const obj1 = {
  name:"zs",
  age:14
}
const obj12 = {
  name:"zsss",
  age:142
}
wset.add(10) //报错:invalid val used
wset.add(obj1)
wset.add(obj12)
console.log(wset);

WeakSet常见的方法:

const wset = new WeakSet();
const obj1 = {
  name: "zs",
  age: 14,
};
const obj2 = {
  name: "zsss",
  age: 142,
};

const obj3 = {
  name: "zsss",
  age: 142,
};
// wset.add(10)
wset.add(obj1);
wset.add(obj2);

console.log(wset.has(obj2)); //true
console.log(wset.has(obj3)); //false,注意

wset.delete(obj2);
console.log(wset.has(obj2)); //false

WeakSet的应用

const wset = new WeakSet();
class Person {
  constructor() {
    wset.add(this);  //将创建的对象保存到weakset中
  }
  running() {
    //每次调用该方法先判断weakset中是否有保证该对象,保证只有Person类的子对象可以调用
    if (!wset.has(this)) {
      throw new Error("不能通过其他类型的对象调用running方法");
    }
    console.log("running", this);
  }
}

Map和WeakMap

Map的使用

const obj = { name: "zs", age: 18, height: 1.88 };
const obj2 = { name: "zsss", age: 11, height: 1.55 };

const map1 = new Map();
map1.set(obj, "abc");
map1.set(obj2, "bcd");
console.log(map1);
/* Map(2) {
  { name: 'zs', age: 18, height: 1.88 } => 'abc',
  { name: 'zsss', age: 11, height: 1.55 } => 'bcd'
} */

console.log(map1.get(obj)); //abc

Map的常用属性方法

Map常见的方法:

WeakMap的使用

WeakMap的常用属性方法:

WeakMap的应用 :

//WeakMap(fkey(对象):value.}):key是一个对象,弱引用
const targetMap = new WeakMap();
function getDep(target, key) {
  //·1.根据对象(target)取出对应的Map对象
  let depsMap = targetMap.get(target);
  if (!depsMap) {
    depsMap = new Map();
    targetMap.set(target, depsMap);
    //·2.取出具体的dep对象
    let dep = depsMap.get(key);
    if (!dep) dep = new Dep();
    depsMap.set(key, dep);
  }
  return dep;
}

上一篇 下一篇

猜你喜欢

热点阅读