1

我有一些数据位于包含图像 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",
                    },

                ]
            }];
4

1 回答 1

2

不要将 data 声明为数组,而是将其声明为对象,同时将 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]);
}
于 2013-11-07T18:14:18.963 回答