gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:47:28 24 4
gpt4 key购买 nike

我有一些数据位于包含图像 url 的数组中。在这里,在数据对象的 img 对象中,我想制作与数组长度一样多的 img(希望有道理吗?)。换句话说,我只是想一遍又一遍地创建一个新对象。您会推荐什么作为解决此问题的最佳方法。我知道这看起来很简单。

  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;

至于每次返回一个对象,我相信如果您返回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]);
}

关于javascript - 在 Javascript 对象中创建新对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843374/

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