gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:44:42 25 4
gpt4 key购买 nike

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);
}

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

最佳答案

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

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"

关于javascript - 为深层嵌套的对象创建和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9038486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com