循环通过容器数组

时间:2013-08-14 04:49:11

标签: javascript createjs

我正在尝试将容器放入容器中,并将其存储在Container容器数组中。听起来令人困惑,所以这是代码:

首先,我制作单独的容器来存储人和动物的BMP和标签:(我将为每个NPC实例创建一个新容器,因为我希望单独控制BMP和相关标签)。

peopleContainer.addChild(peopleBMP, peopleLabel);
animalContainer.addChild(animalBMP, animalLabel);   
animalContainer2.addChild(animalBMP, animalLabel);

然后我为他们分配名称和ID:

peopleContainer.name = "peopleContainer1";
peopleContainer.id = 0;

animalContainer.name = "animalContainer1";
animalContainer.id = 1;

animalContainer2.name = "animalContainer2"; 
animalContainer2.id = 2;

然后我想创建存储这些单独容器的容器:

ContainerOfPeople = new createjs.Container();   
ContainerOfPeople.name = "Container Of People";
ContainerOfPeople.id = 0;
ContainerOfPeople.addChild(peopleContainer);

ContainerOfAnimals = new createjs.Container();  
ContainerOfAnimals.name = "Container Of Animals";
ContainerOfAnimals.id = 1;
ContainerOfAnimals.addChild(animalContainer, animalContainer2);

然后我将这些大容器添加到数组

NPC_Array.push(ContainerOfPeople, ContainerOfAnimals);

现在,我想循环遍历大容器数组,并在大容器中获取容器的各个ID ......这样我就可以检查它们各自的距离,看看哪个最接近玩家。 ..

function checkDistance2() {
   //loop through Containers Array [ContainerOfAnimals, ContainerOfPeople]... 
   for (var index = 0; index < NPC_Array.length; index++) {
        console.log(NPC_Array[index].children[0].name);         
   }            
}

这给出了输出:

peopleContainer1 
animalContainer2

它似乎正在工作,但它正在跳过ContainerOfAnimals中的第一个animalContainer(名称animalContainer1)。那是为什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您没有在NPC_Array[index].children处迭代数组。这解决了:

function checkDistance2() {
   for (var index = 0; index < NPC_Array.length; index++) {
       for (var j = 0; j < NPC_Array[index].children.length; j++) {
           console.log(NPC_Array[index].children[j].name); 
       }
   }            
}

http://jsfiddle.net/mattball/6HGY9