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

130
Vistas
What am I missing in this Javascript Array behavior?

I tried this in the chrome dev tools console:

let a = [[null,null],[null,null]]

function na(){ return Array(2).fill(Array(2)) }
let b = na();

console.log(JSON.stringify(a))
// [[null,null],[null,null]]

console.log(JSON.stringify(b))
// [[null,null],[null,null]]

So far, so good. I was expecting both a and b with the same values and strucuture. Then I wanted to test a small function that should append an extra value in each line:

function add(x) { x.map( line => line.push(null) )}

add(a)
console.log(JSON.stringify(a))
// [[null,null,null],[null,null,null]]

add(b)
console.log(JSON.stringify(b))
// [[null,null,null,null],[null,null,null,null]]
// ?! I was not expecting this extra value here...

Well, that was unexpected. Why is that extra null appearing in add(b) ?

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

0

function na(){
    return Array(2).fill(Array(2))
}

na() fills the empty Array(2) with shallow copies of the second Array(2) object.

As a result changing values in any of the clones changes the Array's value everywhere.

a = Array(5).fill(Array(3))

a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

console.log(JSON.stringify(a))

So because b has 2 elements and you are using .push() to add an element to b for each of the (same) arrays, 2 new elements are added to the 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