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

148
Visualizações
Why does a single assignment to one 2d array cell fill two cells at once in Javascript?

I have this code from this leetcode question:


function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number {
    
    const land: boolean[][] = new Array(n).fill(new Array(n).fill(false))
    console.log(land)
    
    dig.forEach(spot => {
        console.log(spot, spot[0], spot[1])
        land[spot[0]][spot[1]] = true
        console.log(land)
    })
    
    console.log(land)
    return 0

};

With this input

n = 2
artifacts = [[0,0,0,0],[0,1,1,1]]
dig = [[0,0],[0,1]]

With this stdout:

[ [ false, false ], [ false, false ] ]

[ 0, 0 ] 0 0

[ [ true, false ], [ true, false ] ] **but expected => [ [ true, false ], [ false, false ] ]

[ 0, 1 ] 0 1

[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]
[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]

Why do land[1][0] === true and land[1][1] === true when they are never accessed?

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

0

This:

  new Array(n).fill(new Array(n).fill(false))

fills the new outer array with n copies of the same array. The argument to the outer .fill() is computed once, so there's only one array involved for the second dimension.

You can create multiple arrays, one for each row:

const land: boolean[][] = new Array(n);
land.fill("dummy value");
land.forEach((_, i, rows) =>
  rows[i] = new Array(n);
  rows[i].fill(false)
);

In the (edited) code, the outer array is first filled with a dummy value. That's necessary because .forEach() will skip uninitialized entries in an array. Alternatively, a simple for loop could be used, though unless n is enormous it probably doesn't matter.

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