簡體   English   中英

我們可以使用 object 作為 Javascript 中的一個 object 的密鑰嗎?

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

在一次采訪中,我得到了一個簡短的 javascript 代碼,以給出其中的 output,但我不確定其中的 output 是什么。 他創建了一個var object並使用數組數據結構將對象分配為該 object 的索引。 采訪后我確實控制了該代碼,但仍然不明白它是如何顯示 output 的。

這是代碼

 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

任何人都可以用它顯示的 output 背后的 javascript 邏輯來解釋嗎? 提前致謝!

用作鍵的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]"]);

您可以查看 object a ,您會在其中看到字符串 object (使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM