Getting the .length of a object literal
本问题已经有最佳答案,请猛点这里访问。
我怎样才能得到"敌人"的"长度"?我试过很多方法,但都做不到。我想用这个数字来循环穿越敌人。我尝试了object.key()和许多变体,但我不知道如何实现它,也不知道我是否朝着正确的方向前进。
1 2 3 4 5 6 7 8 9 10 11 12 13 | var rooms = { "start": { "description":"You are in a dark, cold place and you see a light to north\ and you hear the sound of running water to the west", "directions": { "north":"clearing1", "west":"bridge1" }, "enemies": { "enemy1":"enemiesDB[0]", "enemy2":"enemiesDB[1]" } } |
}
更新我把代码改成一个数组来解决这个问题。
1 2 3 4 5 6 7 8 9 10 | var rooms = { "start": { "description":"You are in a dark, cold place and you see a light to north\ and you hear the sound of running water to the west", "directions": { "north":"clearing1", "west":"bridge1" }, "enemies": [enemiesDB[0], enemiesDB[1]] } |
号
然后我就可以在这样的循环中使用它…
1 | rooms.start.enemies.length |
谢谢@nickcordova!
对象没有长度,但是可以使用object.keys获取对象的可枚举自有密钥数组,并读取该数组的长度。
敌人是一个没有
埃多克斯1〔2〕
演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 west", "directions": { "north":"clearing1", "west":"bridge1" }, "enemies": { "enemy1":"enemiesDB[0]", "enemy2":"enemiesDB[1]" } } }; console.log(Object.keys(rooms.start.enemies).length); |