Maps vs Objects in ES6, When to use?

后端 未结 6 1742
醉酒成梦
醉酒成梦 2020-11-28 21:55

Ref: MDN Maps

Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.

6条回答
  •  猫巷女王i
    2020-11-28 22:44

    One of the difference between Map and Object is:

    Map can use complex data type as its key. like this:

    const fn = function() {}
    const m = new Map([[document.body, 'stackoverflow'], [fn, 'redis']]);
    
    m.get(document.body) // 'stackoverflow'
    m.get(fn) //'redis'
    

    watch out: For complex data type, If you want to get the value, you must pass the same reference as the key.

    Object, it only accept simple data type(number, string) as its key.

    const a = {};
    a[document.body] = 'stackoverflow';
    
    console.log(a) //{[object HTMLBodyElement]: "stackoverflow"}
    

提交回复
热议问题