如何填充一个空的json对象
我有一个这样的空json对象
var image, description ; var json = { 0 : { image : " " , description : " " } };
我想像这样通过循环n来填充,但是这种添加属性的方式是这个错误:“不能设置undefined的属性描述”
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
,那么这个对象是未定义的。
在使用之前创build空对象:
json[n] = {}; json[n].description = " nth description"; json[n].image = " nth image";
你可以这样编码。
var nt = ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th']; var json = {}; for(var i=0;i<n;i++) { var tp = json[i] = {}; //define first if it a object otherwise it say undefined. tp['image'] = i+nt[(i%10)]+' image'; tp['image'] = i+nt[(i%10)]+' description'; } console.log(json);
你可以这样做:
var json = {} json[n] = {} json[n].description = " ....." json[n].image = " ..... "
您需要在原始内部创build新对象,然后声明其属性。