简体   繁体   中英

looping through multidimensional array innermost loop

I am ultimately trying to create a function that generates some html based on values in a two dimensional(?) array. However, I am struggling to loop through all of the values. In the following code, it is the bottom else clause that my program never enters:

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

When i = 0 and j = 1 doesn't food[i][j] = ['Hero Wedge', "Lettuce, tomato, yada", '$19.42'] ? And since this is an array with 3 elements y < food[i][j] should evaluate to true? Thanks in advance.

You need to check the length of the array and declare all variables.

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

A better approach by iteration from one instead of zero and without a check.

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

The for loop is ranging from y = 0 to y being less than the element at food[i][j] instead of the length of food[i][j] .

Where food[i][j] is "wedges"

So, basically, your for loop would translate to for(y = 0; y < "wedges"; y++){

Hence, replace food[i][j] in the for with food[i][j].length , making the loop as

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

This should solve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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