2

How can I get the "lenght" of "enemies"? I have tried many ways, but I haven´t been able to do it. I want to use the number to loop thru the enemies. I tried Object.key() and many variations, but I don't quiet get how to implemente it, or if I am going on the right direction.

var rooms = {
"start": {
    "description": "You are in a dark, cold place and you see a light to <b>north</b>\
 and you hear the sound of running water to the <b>west</b>",
    "directions": {
        "north": "clearing1",
        "west": "bridge1"
    },
    "enemies": {
      "enemy1": "enemiesDB[0]",
      "enemy2": "enemiesDB[1]"
    }
}

}

UPDATE I change the code to be an array which solved the problem.

    var rooms = {
"start": {
    "description": "You are in a dark, cold place and you see a light to <b>north</b>\
 and you hear the sound of running water to the <b>west</b>",
    "directions": {
        "north": "clearing1",
        "west": "bridge1"
    },
    "enemies": [enemiesDB[0], enemiesDB[1]]
}

Then I was able to use it in a loop like this...

rooms.start.enemies.length

Thanks @NickCordova!

Chris Luna
  • 33
  • 5

2 Answers2

3

Objects doesn't have a length, however you can use Object.keys to get an array of the enumerable own keys of an object, and read the length of that array.

2

Enemies is an object which does not have a length, i guess you want

Object.keys(rooms.start.enemies).length;

DEMO

var rooms = {
  "start": {
    "description": "You are in a dark, cold place and you see a light  and you hear the sound of running water to the <b>west</b>",
    "directions": {
      "north": "clearing1",
      "west": "bridge1"
    },
    "enemies": {
      "enemy1": "enemiesDB[0]",
      "enemy2": "enemiesDB[1]"
    }
  }
};
console.log(Object.keys(rooms.start.enemies).length);
Sajeetharan
  • 186,121
  • 54
  • 283
  • 331