Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda