繁体   English   中英

遍历多维数组最里面的循环

[英]looping through multidimensional array innermost loop

我最终试图创建一个函数,该函数基于二维数组中的值生成一些html。 但是,我正在努力遍历所有值。 在以下代码中,我的程序永远不会输入它是底部的else子句:

let food = [
  [
    'Wedges',
    ['Hero Wedge', "Lettuce, tomato, yada", '$19.42'],
    ['Differebt Wedge', "Chicken, tomato, yada", '$12.42'],
  ],
  [
    'Chicken',
    ['Chicken', "Lettuce, tomato, yada", '$19.42'],
    ['Brocolli Wedge', "Chicken, tomato, yada", '$12.42'],
  ]
]
generate(food);

function generate(food){
  for(i = 0; i < food.length; i++){
    for(j = 0; j < food[i].length; j++){
      if(j === 0){
        sectionName = food[i][j]; // "Wedges"
      }
      else{
        for(y = 0; y < food[i][j]; y++){
          console.log("were in this statment"); //Never runs
        }
      }
    }
  }
}

i = 0j = 1food[i][j] = ['Hero Wedge', "Lettuce, tomato, yada", '$19.42']吗? 既然这是一个包含3个元素的数组,则y < food[i][j]应为true? 提前致谢。

您需要检查数组的长度并声明所有变量。

for(y = 0; y < food[i][j].length; y++){ // use length

一种更好的迭代方法,从一个而不是一个零开始,并且没有检查。

 function generate(food) { var i, j, y, sectionName; for (i = 0; i < food.length; i++) { sectionName = food[i][0]; // assign outside of the loop console.log('sectionName', sectionName); for (j = 1; j < food[i].length; j++) { // start from one for (y = 0; y < food[i][j].length; y++) { // use length console.log(food[i][j][y]); } } } } let food = [['Wedges', ['Hero Wedge', "Lettuce, tomato, yada", '$19.42'], ['Different Wedge', "Chicken, tomato, yada", '$12.42']], ['Chicken', ['Chicken', "Lettuce, tomato, yada", '$19.42'], ['Brocolli Wedge', "Chicken, tomato, yada", '$12.42']]]; generate(food); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

for环是从y = 0y小于所述元件在food[i][j]代替的长度food[i][j]

food[i][j]"wedges"

因此,基本上,您的for循环将转换为for(y = 0; y < "wedges"; y++){

因此,更换food[i][j]forfood[i][j].length ,使得环路

else{
    for(y = 0; y < food[i][j].length; y++) { //take the length of food[i][j]
       console.log("were in this statement"); //Now runs
    }
}

这应该可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM