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

136
Visualizações
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 Respostas
Responde à pergunta

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 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