Using an object as a property key in JavaScript

后端 未结 2 1924
臣服心动
臣服心动 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]".

提交回复
热议问题