gpt4 book ai didi

javascript - 如何填充一个空的json对象

转载 作者:行者123 更新时间:2023-11-30 08:35:54 25 4
gpt4 key购买 nike

我有一个像这样的空 json 对象

var image, description ;

var json = { 0 : { image : " " , description : " " } };

我想通过遍历 n 来像这样填充,但是这种添加属性的方式给出了这个错误:“无法设置未定义的属性描述”

json[n].description = " nth description";
json[n].image = " nth image";

最后我希望var json是这样的

var json = { 0 : {"image" : "1st image", "description" : "2nd description"  }
1 : {"image" : "2nd image", "description" : "2nd description" }
2 : {"image" : "3rd image ", "description" : "3rd description" }
3 : {"image" : "4th image ", "description" : "4th description" }
}

等等.... 我在第一次迭代时遇到未定义的错误,所以我什至还没有尝试添加第二个或第三个元素,所以不确定是否需要其他东西。

最佳答案

因为在您的示例中,如果 n 不是 0,则该对象未定义。

在使用之前创建空对象:

json[n] = {};
json[n].description = " nth description";
json[n].image = " nth image";

关于javascript - 如何填充一个空的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31450752/

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