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

141
Vistas
having different values in the properties of the same object in an array of objects

why i have a value the same object in an array but when i select it like this arr[0] i find in the console diffrent values

class Player {
    constructor(x){
        this.x = x
    }
    move(code){
        if(code==="ArrowUp"){
                this.x +=1;
                fn();
        };
        players[0] = player;
    }
};
let players = [];
let player = new Player(1);
function fn() {
console.log(player,players[0])
}
so when i add an event click for example on the document that when it happen the function of event will call player.move(e.code) and pass as an argument e.code // the value of x of first object in the printed players array is different from the x in the object player1 and players[0]

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

0

Is your problem that you're printing [] undefined?

I reworked your code to give that output:

class Player {
    constructor(x){
        this.x = x
    }
    move(code){
        if(code==="ArrowUp"){
                this.x +=1;
                fn();
        };
        players[0] = player;
    }
};
let players = [];
let player = new Player(1);
player.move("ArrowUp");
function fn() {
    console.log(players,players[0])
}

What happens is inside player, the code is "ArrowUp", triggering the code inside the if to execute. That code increments player.x to 2. By this time, no code has changed anything to do with players, the array, so it is still an empty array []. This is still the case when fn is called after that change to player. The first value printed comes from players being an empty array. The undefined comes from indexing an empty array at 0 (the first element in the array) gives undefined when there is no object there. The result is [] undefined.

Afterward, players[0] = player is ran, putting player at the 0th position in the array. If we run fn at this point, it should output: [ Player { x: 2 } ] Player { x: 2 }. You will get this behavior by putting an fn after players[0] = player or by putting it after player.move("ArrowUp");.

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