Javascript内部数组迭代

时间:2017-07-13 00:27:13

标签: javascript arrays loops foreach iteration

你可以通过迭代数组来帮助我吗? 这是我的代码

https://jsfiddle.net/Ar2zee/9g91ouq6/1/

var projects = {
  "projects" : [[
    "Title : Portfolio",
    "Dates : 2017",
    "Description : Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt voluptatem ex eius sapiente eum quod nostrum esse dolorem sequi deleniti!",
     ["images/1.jpg","images/2.jpg","images/3.jpg","images/4.jpg"]
  ],
  [
    "Title : Social Network",
    "Dates : 2019",
    "Description : Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt voluptatem ex eius sapiente eum quod nostrum esse dolorem sequi deleniti!",
    ["images/1.jpg" , "images/2.jpg" , "images/3.jpg" , "images/4.jpg"]
  ]]
};

for (var i = 0 ; i < projects.projects[3].length; i++) {
  var formattedImage = HTMLprojectImage.replace("%data%",projects.projects[3][i])
}

如何通过图像迭代? 非常感谢你!

2 个答案:

答案 0 :(得分:2)

for (project of projects['projects']) {
  for (image of project[3]) {
    console.log('This is image: ' + image);
  }   
}

这将遍历图像。 [JS Bin]

答案 1 :(得分:0)

projects数据的格式非常尴尬。您是否需要使用此数据格式,或者您是否可以更改数据格式以便更轻松地使用JavaScript?

您数据的更实用的JSON对象可能如下所示:

{
    "projects": [
        {
            "Title": "Portfolio",
            "Dates": "2017",
            "Description": "Lorem ipsum dolor sit amet...",
            "Images": [
                "images/1.jpg",
                "images/2.jpg",
                "images/3.jpg",
                "images/4.jpg"
            ]
        },
        {
            "Title": "Social Network",
            "Dates": "2019",
            "Description": "Lorem ipsum dolor sit amet...",
            "Images": [
                "images/1.jpg",
                "images/2.jpg",
                "images/3.jpg",
                "images/4.jpg"
            ]
        }
    ]
}

如果您被允许更改数据格式,请告诉我,我可以提供更多建议。问题:Dates值的名称表明它可能希望有多个日期,而不仅仅是一个,所以也许它应该是一个数组?