为深层嵌套对象创建和赋值

时间:2012-01-27 18:50:50

标签: javascript

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

function test(){
obj.one=1;
obj.one.two=2;
obj.one.two.three=3;

alert(obj.one);
alert(obj.one.two);
alert(obj.one.two.three);
}

有人可以解释我做错了什么并给我一个更正的例子吗?

4 个答案:

答案 0 :(得分:3)

它更有意义并以这种方式工作:

var obj={
    one:{value:1,
         two:{value:2,
              three:{value:3}
        }
    }
};

function test(){
obj.one.value=1;
obj.one.two.value=2;
obj.one.two.three.value=3;

alert(obj.one.value);
alert(obj.one.two.value);
alert(obj.one.two.three.value);
}

See demo

为什么你的代码不起作用?

这样做:

obj.one = 1;//works till here
obj.one.two = 2;//doesn't work. 
//>> obj.one is "1" and doesn't have any "two" property
obj.one.two.three = 3;//same thing. "two" doesn't exist anyway. 
//Neither does "three"

答案 1 :(得分:2)

test()函数的第一行,您将obj.one的值从对象更改为整数。

答案 2 :(得分:2)

obj.one设置为1时,您会清除“深层嵌套的对象”。

答案 3 :(得分:0)

您不能将属性放在数字值中,因为它们不是对象。

相关问题