在Javascript中在对象中创建新对象的最佳实践

时间:2013-11-07 18:05:27

标签: javascript arrays object

我有一些数据包含在图像的url中。在这里,在数据对象的img对象中,我想制作尽可能多的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",
                    },

                ]
            }];

1 个答案:

答案 0 :(得分:2)

不是将数据声明为数组,而是将其声明为对象,同时将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;

至于每次返回一个对象,我相信如果你返回imgs数组的元素而不是创建新对象会更简单。您的imgs数组已包含对象!

for (var i = 0; i < data.imgs.length; i++) {
    // This will return each object contained within the imgs array
    console.log(data.imgs[i]);
}