javascript - 循环遍历多维数组最内层循环

标签 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 = 1food[i][j] = ['Hero Wedge', "Lettuce, tomato, yada", '$19.42'] ?由于这是一个包含 3 个元素的数组 y < food[i][j]应该评估为真?提前致谢。

最佳答案

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

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

关于javascript - 循环遍历多维数组最内层循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478087/

相关文章:

javascript - 当向下滚动页面时出现和消失元素

javascript - 使用 Javascript 设置 ASP 文字文本

javascript - 使用脚本中的数据,通过排序或警告框的形式编辑 Google 电子表格中的数据

javascript - 如何在 AngularJS 中捕获/处理后端异常

javascript - 如何通过我的 passport.js 链传递参数?

javascript - 谷歌图表 html 工具提示问题

javascript - HTML 属性中的标签?

javascript - 如何更改reactjs中子组件某些部分的所有状态

javascript - 使 <td> 元素中的内容静态位置

javascript - 使用 Express 分解前缀参数