令人困惑的Javascript属性访问者

时间:2015-12-02 18:35:15

标签: javascript

我没有完全理解这一点:

var one = {};
var two = {};
var three = {};

three[one] = "one";
three[two] = "two";

console.log(three[one]); // Alerts "two"

据我了解,JS需要在括号属性表示法中使用一个字符串。所以看起来JS正试图改变:

three[one] = "one";
three[two] = "two";

成:

three[one.toString()] = "one";
three[two.toString()] = "two";

两种toString()方法都没有定义,所以它们最终是相同的值? 不确定我是否明白了。

2 个答案:

答案 0 :(得分:4)

实际上定义了toString方法,并为两者([object Object])生成相同的字符串。



var one = {};
var two = {};
$('body').append(one.toString()+'<br>'+two.toString());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

var one = {};
var two = {};
var three = {};

three[one] = "one";
three[two] = "two";

最后两行说:

three[object] = "one";
three[object] = "two";

因为一个和两个都被声明为对象。

您正在制作的三个对象将如下所示:

[object Object] {
  [object Object]: "two"
}