Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!