获取对象文字的.length

时间:2017-10-23 18:13:50

标签: javascript jquery

我怎样才能获得“敌人”的“长度”?我尝试了很多方法,但我还没能做到。我想用这个数字来穿越敌人。我尝试过Object.key()和许多变种,但我不安静地了解如何实现它,或者我是否朝着正确的方向前进。

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

}

更新 我将代码更改为解决问题的数组。

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

然后我就能在这样的循环中使用它......

rooms.start.enemies.length

谢谢@NickCordova!

2 个答案:

答案 0 :(得分:3)

对象没有长度,但是您可以使用Object.keys来获取对象的可枚举自己的键的数组,并读取该数组的长度。

答案 1 :(得分:2)

敌人 object ,没有 length ,我想你想要

<强> Object.keys(rooms.start.enemies).length;

<强>样本

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);