javascript - I have a question about objects. Can anyone help explain it?
PHP中文网
PHP中文网 2017-06-10 09:48:32
0
2
469

var a={};
var b={key:1};
var c={key:2};
a[b]=3;
a[c] =4;
console.log(a[b]);
I personally think that the content of a[b] should be 3. The above var b and var c are useless, but the actual answer is a[c] is 4, so I can’t understand it. What is the explanation of objects in js? How is this occupied? I hope someone can explain it, thank you very much. . . . . . .

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
黄舟

I guess your question is why the value is overwritten, right?
In Javascript, when accesses object properties through [], the expression in square brackets will be evaluated and converted into a string , call its toString method.
So:

var a = {};
b={key:1};
console.log(b.toString()); // [object Object]
a[b]=3;
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.

伊谢尔伦

Because b.toString() and c.toString() are both [Object object], so they are the same

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!