如何打印此JavaScript数据结构?

时间:2017-09-15 10:47:27

标签: javascript arrays loops

我遇到for循环问题,我只是想在数据结构中打印出细节数组。

  for(i in myObj.detail){
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";  

  for(z=0; z<3; z++){   
     x+="<h2>"+ myObj.detail[i].infor[i].step[z] + "</h2>"; 
     for(m=0; m<3; m++){

       x+="<h2>"+ myObj.detail[i].infor[i].image[m] + "</h2>"; 

         for(c=0; c<3; c++){

            x+="<h2>"+ myObj.detail[i].infor[i].content[c] + "</h2>"; 
           }
        }
     }
 }  



myObj={"detail":[{
         "bigtitle":"Print Room",
         "lable":3,        
         "infor":[{"step":["First","Second","Third"]},
                  {"image":["imge-1","imge-2","image-3"]},
                  {"content":["1111","2222","3333"]}
                 ]}
               }

结果应如下所示:

Print Room 

  First
  image-1
  1111
  Second
  imge-2
  2222
  Third
  image-3
  3333

2 个答案:

答案 0 :(得分:0)

你不需要使用所有这些循环,它们似乎没用,并且会导致许多异常,你只需要2循环:

  • 首先使用myObj.detail循环遍历myObj.detail.length以遍历所有这些数组元素。
  • 第二个循环遍历stepimagecontent条目,使用带有固定计数器的for循环来获取所有这些3条目。

所以你的代码看起来像这样:

var x = "";
for (i in myObj.detail) {
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";
    for (m = 0; m < 3; m++) {
      x += "<h2>" + myObj.detail[i].infor[0].step[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[1].image[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[2].content[m] + "</h2>";
    }
}

<强>演示:

myObj = {
  detail: [{
    bigtitle: "Print Room",
    lable: 3,
    infor: [{
        step: ["First", "Second", "Third"]
      },
      {
        image: ["imge-1", "imge-2", "image-3"]
      },
      {
        content: ["1111", "2222", "3333"]
      }
    ]
  }]
}

var x = "";
for (i in myObj.detail) {
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";
    for (m = 0; m < 3; m++) {
      x += "<h2>" + myObj.detail[i].infor[0].step[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[1].image[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[2].content[m] + "</h2>";
    }
}

document.write(x);

答案 1 :(得分:0)

尝试没有循环cos这个json很容易访问并且很适合管理cpu :)这里的示例:

console.log(myObj.detail[0].bigtitle);
console.log(myObj.detail[0].lable);
console.log(myObj.detail[0].infor[0].step[0]);
console.log(myObj.detail[0].infor[0].step[1]);
console.log(myObj.detail[0].infor[0].step[2]);
console.log(myObj.detail[0].infor[1].image[0]);
console.log(myObj.detail[0].infor[1].image[1]);
console.log(myObj.detail[0].infor[1].image[2]);
console.log(myObj.detail[0].infor[2].content[0]);
console.log(myObj.detail[0].infor[2].content[1]);
console.log(myObj.detail[0].infor[2].content[2]);

https://codepen.io/headmax/pen/RLPLjd?editors=1111