I want to make an array within an array.
It would contain some enemies with all different positions. I tried writing it like this:
var enemies = [
position = {
x: 0,
y: 0
}
];
enemies.length = 6;
This seem to work, however, I don’t know what to write when I want to call it. enemies[1].position.x doesn’t work at all. Any leads?
2 Answers 2
You probably want an array of enemy objects instead. Something like:
var enemies = [
{ position: { x: 0, y: 0 } },
{ position: { x: 0, y: 0 } },
{ position: { x: 0, y: 0 } }
];
var firstEnemy = enemies[0];
firstEnemy.position.x; // 0
var totalEnemies = enemies.length; // 3
1 Comment
What you want to do is
var enemies = [
{
position: { x: 0, y: 0 }
}
];
enemies[0].position.x;
Arrays index starts from 0
Also, let's deconstruct why your code doesn't throw an error, and what it exactly does.
You are declaring an array named enemies, and when declaring it you are defining a global variable named position (and its value is returned)
After execution, enemies look like this [ {x: 0, y: 0} ]
var enemies = [{x:0, y:0}, {x:5, y:5}, {x:10, y:10}];then just refer toenemies[index].xposition).