Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda