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

159
Visualizações
'TypeError: Cannot set properties of undefined (setting '0')'----Array assignment

When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.

        // r and c are already defined numbers,arr is already defined array.
        let n = [[]]
        let index = 0
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                    n[i][j] = arr[index]
                    index++;
            }
        }
        return n; 

Leetcode told me n[i][j] = arr[index] had error;

Anyone knows why? thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Whenever the value of i becomes 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.

the first iteration works fine because there is already an empty array in the 0th index (when i = 0).

here you can try doing this

let n = []
let index = 0
for (let i = 0; i < r; i++) {
    n[i] = [];
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index];
        index++;
    }
}

return n;
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