Iva*_*van 0 javascript arrays for-loop
这是我的代码。我想提取甚至元素。但我所能做的就是4 4 4 4 4。
function f6() {
let out = '';
let a6 = [[1, 2], [3, 4], [5, 6], [21, 34], [44, 56]];
for (let i = 0; i < a6.length; i++) {
for (let i = 0; i < a6[i].length; i++) {
if (a6[i][i] % 2 == 0) {
out += a6[i][i] + ' ';
}
}
}
console.log(out);
}
document.querySelector('button').onclick = f6;Run Code Online (Sandbox Code Playgroud)
<button>Push!</button>Run Code Online (Sandbox Code Playgroud)
为什么?
您已使用相同的变量名称i两次。在内部循环内部声明可以防止您从外部循环let i访问。let i如果您使用不同的变量名称来迭代每个循环,例如j,那么您应该没问题。
如果您只需要使用索引来访问该索引处的值,那么您可能想尝试使用for...of循环来完全避免此问题,例如:
const data = ... // 2D array
for (let row of data) {
for (let cell of row) {
// Use cell here
}
}
Run Code Online (Sandbox Code Playgroud)