Javascript对象属性存在奇怪的平等问题 [英] Strange equality issue with Javascript object properties
问题描述
为什么在执行该代码片段之后:
Why after executing that snippet of code:
var a = {};
var b = {};
var g = {};
g[a] = "aa";
g[b] = "dd";
g [a]的值是dd?
the value of g[a] is "dd"?
a == b是假的,所以这里发生了什么?
a == b is false so what is going on here?
推荐答案
JavaScript对象键只能是字符串。当您存储 g [a] ='aa'
时,使用 toString()
方法将a转换为字符串, 1 所以你实际上在 g [a.toString()] $ c存储
'aa'
$ c>。
JavaScript object keys can only be strings. When you store g[a] = 'aa'
, a is converted to a string using the toString()
method,1 so you're actually storing 'aa'
at g[a.toString()]
.
在这种情况下, a.toString()
是'[ object Object]'
,等于 b.toString()
。
In this case, a.toString()
is '[object Object]'
, which is equal to b.toString()
.
为了使它真的很明显,你问题中的代码等同于:
To make it really obvious, the code in your question is equivalent to this:
var g = {};
g['[object Object]'] = 'aa';
g['[object Object]'] = 'dd';
故事的道德:只是不要尝试使用字符串以外的任何东西作为属性名称。
Moral of the story: just don't try to use anything other than strings as property names.
1 来源: MDC:JavaScript Member Operators - Property Names
1Source: MDC: JavaScript Member Operators - Property Names
这篇关于Javascript对象属性存在奇怪的平等问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!