I searched like 2 hours before asking this question and didn't find anything solving my problem although I think it's a rather basic one. In Java you just can use equal() to see if two objects have the same values. I thought this is how the == operator would work in Javascript. Appearently it does not. :(
I've been trying to compare two own created objects with the == operator, but it returns false although all values were equal. Why?
This is my function for creating the field object I use:
function field(player, figureKind) {
this.player = player;
this.figureKind = figureKind;
this.hidden = true;
if (player == 1 && hidden && figureKind != trapF && figureKind != flagF) {
this.image = figureKind.getImage(0);
} else if (player != 1 && hidden) {
this.image = hidden;
} else {
this.image = figureKind.getImage(player);
}
this.setKind = setKind;
function setKind(figureKind) {
this.figureKind = figureKind;
this.image = figureKind.getImage(player);
}
this.getKind = getKind;
function getKind() {
return this.figureKind;
}
this.getImage = getImage;
function getImage() {
return this.image;
}
this.getPlayer = getPlayer;
function getPlayer() {
return this.player;
}
this.removeHidden = removeHidden;
function removeHidden() {
this.hidden = false;
this.image = figureKind.getImage(player);
if (figureKind == trapF)
this.image = figureKind.getImage(1);
}
}
console.log(new field(2,flagF) == new field(2,flagF));
This returns false although the two objects should be the same, no?
If someone could tell me why this doesn't work AND how to make it work (cause I need this comparison for my game) I would be really thankful!
Answer
The objects are not the same in the mind of JavaScript even if they contain the same elements. Each separately-created object is a unique storage container, and so ==
will return false.
You will need to compare each property of the two objects if you want to see if they contain the same properties.
No comments:
Post a Comment