在Javascript中的对象中创建新对象的最佳实践
我有一些数据在一个包含图像url的数组中。在这里,在数据对象的img对象中,我想制作尽可能多的img作为数组的长度(希望有意义吗?)。换句话说,我只想一次又一次地创建一个新对象。你认为解决这个问题的最佳方法是什么。我知道这看起来很简单在Javascript中的对象中创建新对象的最佳实践,javascript,arrays,object,Javascript,Arrays,Object,我有一些数据在一个包含图像url的数组中。在这里,在数据对象的img对象中,我想制作尽可能多的img作为数组的长度(希望有意义吗?)。换句话说,我只想一次又一次地创建一个新对象。你认为解决这个问题的最佳方法是什么。我知道这看起来很简单 var data = [{ title: "asdfadf", thumb: "images/asdf.jpg", imgs: [{
var data = [{
title: "asdfadf",
thumb: "images/asdf.jpg",
imgs: [{
title: "asdfasdf ",
thumb: "images/asdff.jpg",
img: "images/asdf.jpg",
},
{
title: "asdf",
thumb: "images/asdf.jpg",
img: "images/asdf.jpg",
},
{
title: "Gasdfafafasfasfasfasf. ",
thumb: "images/asdf.jpg",
img: "images/asdf.jpg",
},
{
title: "aswdf",
thumb: "images/asdfD.jpg",
img: "images/asdf.jpg",
},
]
}];
与其将数据声明为数组,不如将其声明为对象,同时保持imgs属性声明为数组:
var data = {
title: "asdfadf",
thumb: "images/asdf.jpg",
imgs: [{
title: "asdfasdf ",
thumb: "images/asdff.jpg",
img: "images/asdf.jpg"
},
{
title: "asdf",
thumb: "images/asdf.jpg",
img: "images/asdf.jpg"
},
{
title: "Gasdfafafasfasfasfasf. ",
thumb: "images/asdf.jpg",
img: "images/asdf.jpg"
},
{
title: "aswdf",
thumb: "images/asdfD.jpg",
img: "images/asdf.jpg"
}
]
};
然后,您可以简单地获取数据对象上imgs
数组属性的值,在其上循环并构建图像,例如:
var html = '';
for (var i = 0; i < data.imgs.length; i++) {
html += 'Image title: ' + data.imgs[i].title;
html += 'Image thumb: ' + data.imgs[i].thumb;
html += 'Image img: ' + data.imgs[i].img + '<br>';
}
// Set the innerHtml only once, when you have built up your whole html
document.getElementById('myDiv').innerHtml = html;
我认为这是最好的做法你在所有地方都有额外的逗号,否则就不可能了<代码>数据[0]。imgs[i]我没有说这不可能:)我只是想给他提供我自己的版本。我认为声明一个对象比像他那样声明要好得多。就我的两分钱!:)
for (var i = 0; i < data.imgs.length; i++) {
// This will return each object contained within the imgs array
console.log(data.imgs[i]);
}