Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Why can't I do proper iteration over two-dimensional array?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!