我最终试图创建一个函数,根据二维(?)数组中的值生成一些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 = 0
和j = 1
不
food[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/