Maps vs Objects in ES6, When to use?

后端 未结 6 1739
醉酒成梦
醉酒成梦 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条回答
  •  生来不讨喜
    2020-11-28 22:29

    This question is a duplicate of but until it's closed, here's my answer from over there:

    In addition to the other answers, I've found that Maps are more unwieldy and verbose to operate with than objects.

    obj[key] += x
    // vs.
    map.set(map.get(key) + x)
    

    This is important, because shorter code is faster to read, more directly expressive, and better kept in the programmer's head.

    Another aspect: because set() returns the map, not the value, it's impossible to chain assignments.

    foo = obj[key] = x;  // Does what you expect
    foo = map.set(key, x)  // foo !== x; foo === map
    

    Debugging maps is also more painful. Below, you can't actually see what keys are in the map. You'd have to write code to do that.

    Objects can be evaluated by any IDE:

提交回复
热议问题