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)
indexOf, it checks for the reference of the object, not its content.findIndexwith custom equality checkconst a = {}, b = {},a === aistrue, buta === bis not. SinceindexOfuses===for comparison, you cannot use it in your case.