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?

7
  • 1
    Your first element would be enemies[0] Commented Sep 15, 2015 at 12:24
  • Your “array” is invalid syntax. Commented Sep 15, 2015 at 12:24
  • var enemies = [{x:0, y:0}, {x:5, y:5}, {x:10, y:10}]; then just refer to enemies[index].x Commented Sep 15, 2015 at 12:25
  • 1
    @Xufox It's not invalid, he's just creating a global (position). Commented Sep 15, 2015 at 12:25
  • 2
    possible duplicate of Access / process (nested) objects, arrays or JSON Commented Sep 15, 2015 at 12:26

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @nikhil. Completely missed that.
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} ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.