gpt4 book ai didi

javascript - 将 for in 循环更改为 for 循环

转载 作者:行者123 更新时间:2023-11-30 11:44:37 26 4
gpt4 key购买 nike

假设我有一个名为项目的对象。 projects 对象有一个名为 projects 的键,它是 2 个其他对象的数组。其他 2 个对象中的每一个都有一个图像数组。我能够使用 for in 循环遍历每个对象数组中的每个图像,但我想改用 for 循环或 forEach。我能做些什么?这是我的代码:

var projects = {};

projects.projects = [
{
"title": "mycode",
"dates": "mycode",
"description": "mycode",
"images": ["http://lorempixel.com/400/200/", "http://lorempixel.com/350/150/", "http://lorempixel.com/500/300/"]
},

{
"title": "mycode",
"dates": "mycode",
"description": "mycode",
"images": ["http://lorempixel.com/400/200/", "http://lorempixel.com/350/150/", "http://lorempixel.com/500/300/"]
}

];

projects.display = function() {

for (var i = 0; i < projects.projects.length; i++) {

var formattedProjectTitle = HTMLprojectTitle.replace("%data%", projects.projects[i].title);
$(".project-entry:last").append(formattedProjectTitle);

var formattedProjectDates = HTMLprojectDates.replace("%data%", projects.projects[i].dates);
$(".project-entry:last").append(formattedProjectDates);

var formattedProjectDescription = HTMLprojectDescription.replace("%data%", projects.projects[i].description);
$(".project-entry:last").append(formattedProjectDescription);

//Iterate through each image in the projects objects.

for (image in projects.projects[i].images) {
var formattedProjectImages = HTMLprojectImage.replace("%data%", projects.projects[i].images[image]);
$(".project-entry:last").append(formattedProjectImages);
}

}

}

最佳答案

您可以使用嵌套的 for 循环来做到这一点

for (var i = 0; i < projects.projects.length; i++) {
for (var j = 0; j < projects.projects[i].images.length; j++) {
var x = projects.projects[i].images[j];
console.log(x);
}
}

关于javascript - 将 for in 循环更改为 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41429641/

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