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

144
Vistas
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 Respuestas
Responde la pregunta

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