【问题标题】:Detecting if a property value exists in an array of objects检测对象数组中是否存在属性值
【发布时间】:2012-07-27 16:21:08
【问题描述】:

我正在尝试检查容器“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); 

【问题讨论】:

    标签: javascript arrays oop prototype exists


    【解决方案1】:

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

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

    for(var i = 0; i < members.length; i++) {
        EntityID == members[i].EntityID;
    }
    

    【讨论】:

      【解决方案2】:

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

      如果你用下面的代码替换这个循环,你应该没问题:

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

      【讨论】:

        猜你喜欢
        • 2020-11-30
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        • 2018-04-10
        • 2017-03-22
        相关资源
        最近更新 更多