获取对象字面量的长度

3

我该如何获取“enemies”的“长度”? 我尝试了很多方法,但都没有成功。 我想使用这个数字来循环遍历敌人。 我尝试了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!

{btsdaf} - Pointy
{btsdaf} - Chris Luna
{btsdaf} - Felix Kling
{btsdaf} - Chris Luna
{btsdaf} - Chris Luna
显示剩余5条评论
2个回答

3

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


{btsdaf} - Chris Luna
Object.keys(rooms.start.enemies).length - user8811940

2

敌人是一个对象,它没有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);


{btsdaf} - Chris Luna
which line throws the error - Sajeetharan
{btsdaf} - user8811940

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接