当我运行下面的 JavaScript 代码时,前两行输出是:
5
undefined
为什么第二个输出行是未定义的而不是 5?这是代码:
matrix = [
[2, 5, 7],
[4, 6, 1],
[7, 3, 9]
];
for (var i in matrix) {
for (var j in matrix[i]) {
console.log(matrix[0][0 + 1]);
console.log(matrix[i][j + 1]);
}
}
最佳答案
o不确定您为什么要 +1。这导致了你的问题。
还包含 array.forEach
。
包含基于 Ibrahim 评论的修复
matrix = [[2, 5, 7], [4, 6, 1], [7, 3, 9]];
for(let i of matrix){
for(let j of i){
console.log(j);
}
}
matrix.forEach(m => {
m.forEach(e => console.log(e));
});
关于javascript - 如何在索引中使用表达式时遍历数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000617/