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])
}
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");.