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

147
Visualizações
Javascript: Push function behave differently with array with reference and without reference

I am getting two different results for doing which I believe is the same thing in javascript with array push. Since I am new to javascript, I might be missing the big picture here.

Sample 1 -

class Test {

    constructor(){
        this.matrix = [];
    }

    createMatrix(){
        this.matrix.push([0,0,0]);
        this.matrix.push([0,0,0]);
        this.matrix.push([0,0,0]);
    }

    addNodes(x, y){
        this.matrix[x][y] = 1;
        this.matrix[y][x] = 1;
    }

    printMatrix(){
        return this.matrix;
    }
}

let test = new Test();
test.createMatrix();
console.log(test.printMatrix());
test.addNodes('1','2');
console.log(test.printMatrix());

O/p -

[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]

Sample 2 -

Replacing the createMatrix method with below one, gives me another result when trying to addNodes.

createMatrix(){
        let row = [0,0,0];
        this.matrix.push(row);
        this.matrix.push(row);
        this.matrix.push(row);
    }

O/p -

[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

[ [ 0, 1, 1 ], [ 0, 1, 1 ], [ 0, 1, 1 ] ]

Please help me understand what I am missing out here, I want to achieve is o/p of sample 1 with the sample 2 code.

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

0

it is a matter of reference. In the second example, you are inputting the same array 3 times with the push function. The 3 arrays are pointing to the same memory address, which is referenced by the variable rows.

In the first example there are 3 different arrays, with 3 different memory addresses

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