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

122
Visualizações
problem with js loops and array of objects

I have a question about js loops and how they really work. I'm looping trough an array of objects that looks like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

The loop just updates the value of every element:

array.forEach(el => {
        el.value = 1;
        console.log(array)
})

The thing that I don't understand is why the output looks like this:

[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

And not like this:

[{value: 1}, {value: 0}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

What am I missing?

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

0

I'm guessing that you are trying to look at the output on the dev tools on Chrome, and on the dev tools, you see a reference to the array. meaning that at the end of the execution all the items have value = 1, so the dev tools shows your the same reference to the array.

To see the actual values at the moment of execution (instead of reference) use JSON.stringify like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

array.forEach(el => {
        el.value = 1;
        console.log(JSON.stringify(array))
});
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