0

I'd like to loop through data from two arrays to check if any of the data's distance is close to the player.

Container arrays (only 1 element in each right now):

peopleContainers_Array.push(peopleContainer);
animalContainers_Array.push(animalContainer);   

I've loaded two arrays of create js containers into NPC_Array:

NPC_Array.push(peopleContainers_Array, animalContainers_Array); 

And would like to loop through both as such to get the x,y values of data elements in the container arrays.

for (npc_array in NPC_Array) {
     //NPC_Array(peopleContainers_Array, animalContainers_Array);
    for (container in NPC_Array[npc_array]) {
        console.log(NPC_Array[npc_array[container].x]); //outputs undefined
    }
}

Why wouldn't this work?

Thanks!

user3871
  • 12,432
  • 33
  • 128
  • 268
  • 3
    Side note: You may want to read through "[Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/q/500504)" – Jonathan Lonowski Aug 14 '13 at 03:05

1 Answers1

1
for (npc_array in NPC_Array) {
     //NPC_Array(peopleContainers_Array, animalContainers_Array);
    for (container in NPC_Array[npc_array]) {
        console.log(NPC_Array[npc_array][container].x);
    }
}

I think it should be like this.

Well,replace for ... in:

for (var index=0;index<NPC_Array.length;index++) {
     //NPC_Array(peopleContainers_Array, animalContainers_Array);
    for (var childIndex=0;childIndex<NPC_Array[index].length;childIndex++) {
        console.log(NPC_Array[index][childIndex]['x']);
    }
}
Fly_pig
  • 155
  • 8
  • Aside from using a `for...in` loop when a regular `for` loop, yes. – Matt Ball Aug 14 '13 at 03:12
  • @MattBall What's wrong with using `for...in`? I want to get the objects within an array; isn't that what it's used for? Maybe I don't know the difference of when to use `for...in` vs `for` – user3871 Aug 14 '13 at 03:22
  • 3
    @Growler [scroll up.](http://stackoverflow.com/questions/18222519/looping-through-array-of-arrays-why-wont-this-work/18222548?noredirect=1#comment26712856_18222519) – Matt Ball Aug 14 '13 at 03:43
  • @Growler `for...in` is used to iterate members of objects rather than array, if did it, unpredictable issues may come up.See the [link](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) Jonathan Lonowski gave in the comment. – Fly_pig Aug 14 '13 at 03:44