Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda