2
var test = {
    one: {},
    two: {},
};
test['two'].parent = test['one'];

我想要测试有什么:

test = {
   one: {},
   two: { parent: {}, }

它实际上有什么:

 test = {
    parent: {},
    two: { parent: {}, }

为什么 test.one 变成 test.parent?

我希望 test.two.parent 持有对 test.one 的引用。我该怎么做?

4

3 回答 3

3

你使用的是什么浏览器?它可能会有所作为。

我在 Firefox 上的 Firebug 中收到了预期的结果测试,但是我不建议混合和匹配属性访问语法(语法?语法?)。

代替:

test['two'].parent = test['one'];

我会做:

test['two']['parent'] = test['one'];
于 2011-01-24T17:33:59.003 回答
3

为什么 test.one 变成 test.parent?

它没有。生成的结构是:

{
one: {},
two: { parent: {} }
}

在哪里parent引用与所引用的相同的对象one

如果你这样做:

test.one.cheese = "crackers";

...下面的结果将是“饼干”

alert(test.two.parent.cheese); // "crackers"

示例:http: //jsfiddle.net/g5chF/

于 2011-01-24T17:34:06.783 回答
1

您对本声明的作用的主张:

test['two'].parent = test['one'];

是不正确的。代码已经做了你想要的:它添加了一个“父”属性到test.two,所以在test.two.parent.

于 2011-01-24T17:33:39.003 回答