0

BETTER ANSWERS HERE They aren't equal because with objects js checks for the reference not the value.

I have an object in an array, and the array is iterated through, running a method on each of the elements (which are all the same class). In the method it tries to get the element's index in the array: const index = game.players.indexOf(this) This obviously should return the index, since no modifications to the element have been made (its one of the first lines in the method), however it returns -1

So I put in this line: console.log(game.players[0], this, game.players[0] == this) It gave me the two identical-looking objects, and false. I spent a couple minutes double and triple checking both objects for differences, eventually just searched up a text difference checker and...the two objects are identical?? (i included the whole objects incase anyone wanted to see them) What???? is this some weird behind the scenes memory thing I dont know about?? I tried both === and ==, both returned false.

Here is all the relevant code:

//iterating through the loop for (let i in this.players) { let actionChance = 1 while (Math.random() <= actionChance) { // run newAction() on each item result.push(this.players[i].newAction(this.players.length)) actionChance *= 0.6 } } 
newAction(players, round) { //getting the parent object which is iterating through the array and running this method const data = require('./data.json') //the game is saved to data.json as a string, and then i have a static method to convert the parsed object to an instance of the game class let game = Game.toGame(JSON.parse(data[this.gameID])) //get the index const index = game.players.indexOf(this) 
5
  • Objects are not the same instance, even though their content might be identical. Keeping the above statement in mind, when you use indexOf, it checks for the reference of the object, not its content. Commented Feb 2, 2024 at 7:06
  • Javascript check for reference, not the content. They are stored in different locations in memory, so they are not the same, even though they both look identical Commented Feb 2, 2024 at 7:07
  • You will need to use findIndex with custom equality check Commented Feb 2, 2024 at 7:07
  • 1
    Does this answer your question? Why are two objects with the same values not equal? Commented Feb 2, 2024 at 7:07
  • Two objects are never equal, unless they are the same object. I.e. given const a = {}, b = {}, a === a is true, but a === b is not. Since indexOf uses === for comparison, you cannot use it in your case. Commented Feb 2, 2024 at 7:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.