javascript output value
迷茫
迷茫 2017-06-12 09:30:19
0
3
662

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.

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
黄舟

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.

曾经蜡笔没有小新

a[b]=123; After this step, print console.log(a); you will suddenly understand

phpcn_u1582

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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!