1

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

2 Answers2

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
Andy
  • 61,948
  • 13
  • 68
  • 95
1

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} ]

axelduch
  • 10,769
  • 2
  • 31
  • 50