Sunshine168 / resume

My resume
3 stars 1 forks source link

Map & WeakMap #19

Open Sunshine168 opened 5 years ago

Sunshine168 commented 5 years ago

Map

Map的使用主要就是围绕key跟value

The keys of an Object are String and Symbol, whereas they can be any value for a Map, including functions, objects, and any primitive.

所以说key可以是一个对象,一个字符串,或者说是一个Symbol

初始化一个 Map

const map = new Map([['mike',18],['jake','20']]);
map.size //获取长度

需要介绍的方法(除get,has,clear忽略)

  map.entries() // 返回一个遍历map每个元素的迭代器
  map.keys(); // 返回一个遍历map中所有key的迭代器
  map.values();// 返回一个遍历map中所有value的迭代器
  map.forEach((value, key, map)=>{console.log(`value:${value}, key:${key}`)})

迭代器

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the Iterator protocol by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should simply continue to return {done: true}

简单来说一个迭代器创建之后,是通过next方法不断获取值,当返回的对象里done属性是true的时候代表这个迭代器已经执行完毕,而返回对象中的value则是当次迭代器返回的值

下面举出一个例子

function runIterators(i) {
  let buoy = i.next();
  while (!buoy.done) {
    console.log(buoy.value);
    console.log(buoy);
    buoy = i.next();
  }
}

let map = new Map([["a", 1], ["b", 2], ["c", 3]]);

var keys = map.keys();

runIterators(keys);

需要不断的通过的获取下一个迭代器进行遍历

WeakMap

WeakMap 也是Map的一种,但是在方法和使用上又有一些不同

  1. WeakMpa的Key只能是对象,非对象则会报错。
  2. 当作为WeakMap Key的对象没有其他引用的时候,该键与所指向的值都会被移除(我的理解是Key被回收,value如果是引用的话就看其他地方是否还有引用,否则也是回收,他们的表现是在这个WeakMap中消失)
  3. WeakMap 没有keys、values、entries方法,也没有size属性。因为在V8中垃圾回收的执行时间是不可预知的,有可能在遍历的过程中垃圾回收就执行了,这个键名就消失了,所以WeakMap只可以使用 get、set、has、delete

WeakMap的使用场景

一个比较有意思的使用场景,就是用来实现私有变量

const wm = new WeakMap();

class A {
  constructor(number) {
    wm.set(this, { number });
  }
  getNumber() {
    return wm.get(this).number;
  }
}

const a = new A(1);

console.log(a.getNumber());

附上一个介绍WeakMap比较详细的一个链接 https://zhuanlan.zhihu.com/p/25454328