1

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); 

2 Answers 2

3

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 Entity objects, the member variable is referring to the index of those objects which is 1 and 2 respectively. The correct way to iterate through those objects is:

for(var i = 0; i < members.length; i++) {
    EntityID == members[i].EntityID;
}
Sign up to request clarification or add additional context in comments.

Comments

3

The problem is your for...in loop. You should only use for...in when iterating over properties in an object, not through items of an array.

If you replace this loop with the following, you should be fine:

for(var i=0,len=members.length; i<len; ++i){
     var member = members[i];
     //the rest

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.