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

184
Vistas
Weird behavor of generated object with arrays

I am trying to create a generative object, filled with arrays (all 0).

//declaration of the data object
var data = {}

//initiate to fill data with keys and arrays
function init()
{
 var pos = Array.apply(null,Array(16)).map(Number.prototype.valueOf,0); //creates empty array filled with 0
 for(var i = 0; i < 16; i++) {
  data[i] = pos;
 }
}

init();

console.log(data);

This would give me a data filled with keys from 0 to 2 and each key has an array filled with 0;

{
  '0': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '1': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '2': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ]
}

Now, when I try to modify a specific array like this:

data[0][1] = 1;

then the result will print that all arrays in all keys have been modified...

{
  '0': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '1': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '2': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ]
}

This makes no sense to me because I wanted to modify only the first array with key 0... If I create the whole object manually, the change will work fine, but if I do it this way (generative), I get this strange bug. Any ideas?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It is because every key in data is referencing to the same array. Array is an object. When you assing object to some variable, or pass it as argument, you just pass it refference.

To make your code to work correctly as you like, you have to generate new array every time, you want to assign it to some key in data.

const data = {};

for (let i = 0; i < 16; i++) {
  data[i] = new Array(16).fill(0);
}
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