1

特定の「ID」を持つ「メンバー」オブジェクトが、コンテナー「EntityGroup」オブジェクトの「メンバー」配列に既に存在するかどうかを確認しようとしています。次の 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)配列内のオブジェクトを反復処理するための適切な構造ではありません。オブジェクトのキーのみを反復処理するために使用することを意図しています。

つまり、変数は2 つのEntityオブジェクトを取得する代わりに、それぞれ と であるオブジェクトのインデックスを参照しています。これらのオブジェクトを反復処理する正しい方法は次のとおりです。member12

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 に答える