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

149
Visualizações
Change value of element inside nested array, array created with Array().fill()

Consider the code below. I want to change only the second elements value in the second list in matrix. The problem is, that somehow all elements are changed. How can this be?

let matrix = Array(2).fill(Array(2).fill(0));
// [[0, 0], [0, 0]]
matrix[1][1] = 8
console.log(matrix)
// [[0, 8], [0, 8]]

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

0

This is because all elements inside matrix are pointing to or referencing the same list. By wanting to change one instance of the list, you change them all because you thereby change the list being pointed to. To avoid this, create an empty nested array using for-loops instead:

let matr = [];
for (let i = 0; i < 2; i++) {
  matr.push(Array(2).fill(0))
}
matr[1][1] = 8
console.log(matr)

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