Here's my code. I wanna pull up even elements. But all I can pull up is 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;
<button>Push!</button>
Why?
You've used the same variable name, i, twice. Declaring let i inside your inner loop prevents you from accessing the let i from your outer loop. If you use a different variable name for iterating through each loop, e.g. j, then you should be fine.
If you only need to use the index for accessing values at that index, then you may instead want to try a for...of loop to avoid this problem altogether, e.g.:
const data = ... // 2D array
for (let row of data) {
for (let cell of row) {
// Use cell here
}
}
Your placeholder variable i is getting Shadowed by the second iteration, therefore you may want to use another placeholder such as j to have the correct reference to the element.
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 j = 0; j < a6[j].length; j++) {
if (a6[i][j] % 2 == 0) {
out += a6[i][j] + ' ';
}
}
}
console.log(out);
}
document.querySelector('button').onclick = f6;
<button>Push!</button>