在for循环中返回实例的id

时间:2016-04-10 17:11:09

标签: javascript

我有以下内容:

function Bee(name, id, lifespan, hitPoints) {
    this.name = name;
    this.id = id;
    this.lifespan = lifespan;
    this.hitPoints = hitPoints;
    Bee.numInstances = (Bee.numInstances || 0) + 1;

    return this;
}

内部文件已准备就绪:

$(document).ready(function(){

    var BEE = BEE || {};

    BEE.QueenBee = new Bee('QueenBee', 1, 100, 8);

    BEE.WorkerBee = new Bee('WorkerBee1', 2, 75, 12);
    BEE.WorkerBee = new Bee('WorkerBee2', 2, 75, 12);
    BEE.WorkerBee = new Bee('WorkerBee3', 2, 75, 12);
    BEE.WorkerBee = new Bee('WorkerBee4', 2, 75, 12);
    BEE.WorkerBee = new Bee('WorkerBee5', 2, 75, 12);

    BEE.DroneBee = new Bee('DroneBee1', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee2', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee3', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee4', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee5', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee6', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee7', 3, 50, 12);
    BEE.DroneBee = new Bee('DroneBee8', 3, 50, 12);

    //$('button').on('click', ba);

    for(i = 0; i < Bee.numInstances; i++){
        console.log(Bee.id === 2);
    };

});

我的console.log返回14 false。我想检查/制作循环并仅返回ID为2的每个实例,因此“Bee.id === 2”

2 个答案:

答案 0 :(得分:2)

要继续蜜蜂主题,您可以创建一个蜂巢,您可以添加蜜蜂,并根据他们的id返回蜜蜂。

function Hive() {}

Hive.prototype.bees = [];

Hive.prototype.addBee = function (bee) {
  this.bees.push(bee);
};

Hive.prototype.getBeeIds = function (id) {
  if (!id) return this.bees;
  return this.bees.filter(function (bee) {
    return bee.id === id;
  });
}

var hive = new Hive();

添加蜜蜂:

hive.addBee(new Bee('WorkerBee1', 2, 75, 12));
hive.addBee(new Bee('DroneBee1', 3, 50, 12));

使用id参数检索具有getBeeIdsid来电hive.getBeeIds(2); 的蜜蜂。

getBeeIds

要检索所有蜜蜂,请在没有id参数的情况下致电hive.getBeeIds();

$(document).ready(function(){

    var BEES = [];

    BEES.push(new Bee('WorkerBee1',2,75,12);
    BEES.push(new Bee('WorkerBee2',2,75,12);
    BEES.push(new Bee('WorkerBee3',2,75,12);

    var selectedBees = BEES.filter(function(bee){
       return bee.id == 2;
    });

    console.log(selectedBees); //Should log Array of all 3 bees

});

DEMO

答案 1 :(得分:1)

首先,您尝试将多个对象分配给对象的一个​​键。那样不行。您应该使用对象数组。为了过滤掉正确的,我建议使用Array.filter()函数:

selectedBees

map函数采用一个回调函数,该函数为您要过滤的Array的每个条目调用。如果函数对某个项返回true,则会将其推送到最终的ToString数组中。如果错误没有任何反应。

修改

我用map而不是filter。地图工作不同,只是看到了错误并修复了它!