1

我正在尝试检查容器“EntityGroup”对象的“members”数组中是否已经存在具有特定“ID”的“member”对象。为什么以下 EntityGroup.idExists(id) 不起作用:

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

2 回答 2

3

for (x in y)不是遍历数组中对象的正确构造。它仅用于迭代对象的键。

所以发生的事情是,变量不是获取两个Entity对象,而是分别member引用这些对象的索引。遍历这些对象的正确方法是:12

for(var i = 0; i < members.length; i++) {
    EntityID == members[i].EntityID;
}
于 2012-07-30T00:17:26.957 回答
3

问题是你的for...in循环。您应该只for...in在迭代对象中的属性时使用,而不是通过数组的项目。

如果你用以下内容替换这个循环,你应该没问题:

for(var i=0,len=members.length; i<len; ++i){
     var member = members[i];
     //the rest
于 2012-07-30T00:17:37.043 回答