我们可以使用 object 作为 Javascript 中对象的键吗?

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

我在一次采访中得到了一个简短的 javascript 代码来给出它的输出,但我不确定它的输出是什么。他创建了一个 var object 并使用数组数据结构将对象分配为该对象的索引。我在采访后控制了该代码,但仍然不明白它是如何显示输出的。

这是代码

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

任何人都可以用 javascript 输出背后的逻辑来解释一下吗? 提前致谢!

您可以查看对象 a,在那里您可以看到带弦的对象(带有 toString()

[object Object]

作为访问者。

对象只能有字符串作为属性,最新的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);

作为key的toString的对象是[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]"]);