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

时间:2019-06-06 12:56:49

标签: javascript

我最终试图创建一个函数,该函数根据二维数组中的值生成一些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 = 1时 不     food[i][j] = ['Hero Wedge', "Lettuce, tomato, yada", '$19.42']?并且由于这是一个包含3个元素的数组,y < food[i][j]的计算结果应为true?提前致谢。

2 个答案:

答案 0 :(得分:1)

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

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

一种更好的迭代方法,可以从1而不是0进行迭代,而无需检查。

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; }

答案 1 :(得分:0)

for循环的范围从y = 0y,小于food[i][j]上的元素,而不是food[i][j]的长度。

food[i][j]"wedges"的地方

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

因此,将food[i][j]中的for替换为food[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
    }
}

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