Using an object as a property key in JavaScript

后端 未结 2 1923
臣服心动
臣服心动 2020-12-11 06:11

What is going on in this code?

var a = {a:1};
var b = {b:2};
var c = {};

c[a] = 1;
c[b] === 1 // true!

c[b] = 2;
c[a] === 2 // true!

Spec

相关标签:
2条回答
  • 2020-12-11 06:23

    Why you use an object as a key, the key is becoming the object.toString() 's result which is [Object Object],

    So what you are dothing is set a value to the property "[Object Object]", and get the value by the property "[Object Object]".

    0 讨论(0)
  • 2020-12-11 06:25

    What does it mean to use an object as a key to a property in JavaScript?

    Javascript objects only allow string keys, so your object will first be coerced to a string.

    Specifically, why does using looking up b in c return the value that was stored in a property of a?

    The string representation of {a: 1} and {b: 2} are both "[object Object]", thus, the property is overwritten.

    Edit: If you really need to use objects as keys (I would prefer another solution, if possible), you could use the object's JSON representation:

    c[JSON.stringify(a)] = 1
    c[JSON.stringify(b)] = 2
    

    But, again, try to think of a different approach. Perhaps the objects have unique identifiers other than the object itself.

    0 讨论(0)
提交回复
热议问题