简体   繁体   English

我们可以使用 object 作为 Javascript 中的一个 object 的密钥吗?

[英]Can we use object as a key of an object in Javascript?

I was given a short javascript code in an interview to give the output of that but I was not sure what will be the output of that.在一次采访中,我得到了一个简短的 javascript 代码,以给出其中的 output,但我不确定其中的 output 是什么。 He creates a var object and assigns objects as indexes of that object using the array data structure.他创建了一个var object并使用数组数据结构将对象分配为该 object 的索引。 I did console that code after the interview but still do not understand how it is showing the output.采访后我确实控制了该代码,但仍然不明白它是如何显示 output 的。

Here is the code这是代码

 var a = {}; b = { key: 'b'}; c = { key: 'c'}; a[b] = 123; a[c] = 456; console.log(a[b]); //what is the output of this console statement and explain why

Can anyone explain with javascript logic behind the output it shows?任何人都可以用它显示的 output 背后的 javascript 逻辑来解释吗? Thanks in advance!提前致谢!

The object used as key's toString is [object Object] and that is what is used each time用作键的toString的 object 是[object Object] ,这就是每次使用的内容

 var a = {}; b = { key: 'b'}; c = { key: 'c'}; a[b] = 123; // sets a["[object Object]"] console.log(b,a[b]) a[c] = 456; // ALSO sets a["[object Object]"] console.log(b,a[b]) console.log(Object.keys(a)) console.log(a[b]); console.log(a["[object Object]"]);

You could have a look to the object a , where you see the stringed object (with toString() )您可以查看 object a ,您会在其中看到字符串 object (使用toString()

[object Object]

as accessor.作为访问者。

Objects can have only strings as properties and with the latest Symbol , it could be this one, too.对象只能将字符串作为属性,而最新的Symbol也可能是这个。

 var a = {}; b = { key: 'b'}; c = { key: 'c'}; a[b] = 123; a[c] = 456; console.log(a[b]); //what is the output of this console statement and explain why console.log(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM