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
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 Respostas
Responde à pergunta

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