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

201
Visualizações
Is there a reason why multiple array elements are changing simultaneously after updating just one?

While attempting to make a change to a single array element by adding a string to it, it then updates the rest of the array elements with the same string value. Instead of changing a single element, it has updated the rest of the array with the same value.

I have tried to find an explanation of why more than one array element is changing without a loop, but it does not look possible without .apply, ..., or a loop:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[3][0] = 'bar';
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ]
]

What I expected:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[3][0] = 'bar';
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], []
]

Btw, this also works:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[4][0] = 'bar'; // Changed from myArray[3][0] to myArray[4][0]
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ]
]
about 4 years ago · Juan Pablo Isaza
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