I am trying to check if a ‘member’ object with a specific ‘ID’ already exists in the ‘members’ array of a container ‘EntityGroup’ object. why doesn’t the following EntityGroup.idExists(id) work:
EntityGroup = function() {
this.members = []; // intention is for this to hold 'Entity' objects
this.classType = null; // what class of entities does it hold
};
EntityGroup.prototype = {
addEntity: function(entityType, EntityID) {
// TODO implement .idExists() check here
// dont add new member if the id does exist
this.members.push(new Entity(entityType, EntityID))
},
idExists: function(EntityID) {
var idExists = false,
member,
members = this.members;
for (member in members) {
if (EntityID == member.EntityID) {
idExists = true;
break;
} else {
continue;
}
}
return idExists;
}
};
Entity = function(entityType, EntityID) {
this.EntityID = EntityID;
this.entityType = entityType;
};
g = new EntityGroup();
g.addEntity("Person", 1);
g.addEntity("Person", 2);
console.log(g.idExists(1)); // returns false which is not expected
console.log(g.members);
for (x in y)is not the right construct to iterate through objects in an array. It is meant to be used for iterating through keys of an object only.So what is happening is that instead of getting the two
Entityobjects, themembervariable is referring to the index of those objects which is1and2respectively. The correct way to iterate through those objects is: