var a={},
b={key:'b'},
c={key:'c'};
a[b]=123;
a[c]=456;
console.log(a[b]);//The output is 456.
I don’t understand why the output result is 456. Please help me explain it.
黄舟2017-06-12 09:32:19
In Javascript, when accesses object properties through []
, the expression in square brackets will be evaluated and converted into a string , calling its toString
method.
So:
var a = {};
b={key:'b'};
console.log(b.toString()); // [object Object]
a[b]=123;
console.log(typeof Object.keys(a)[0]); // string, 属性名 b 转换成了字符串.
So b
and c
are converted into the same string [object Object]
. So it will be overwritten if assigned again.
曾经蜡笔没有小新2017-06-12 09:32:19
a[b]=123; After this step, print console.log(a); you will suddenly understand
phpcn_u15822017-06-12 09:32:19
If you treat object b
as an attribute of a
, the toString()
method of object b
will be called first.
var b={key:'b'};
b.toString(); // '[object Object]'
So,
a[b] = 123;
// 即为
a['[object Object]'] = 123;
// 同理,下面一步赋值操作 c 也会先转换,然后再次更新属性 '[object Object]'对应的值
a['[object Object]'] = 456;