在我正在制作的文字冒险游戏中,我的房间对象字面量看起来像这样:
room : {
// some info,
exits : {
north : -1,
east : "house",
south : "forest",
west : -1
}
}
在我的移动函数中,它说:
if (room["exits"][direction] !== -1) {// go that way}
else {print "you can't go that way!"}
现在我想通过测试对象中是否存在相关方向的键来节省空间。因此,字面量将变为:
room : {
// some info,
exits : {
east : "house",
south : "forest"
}
}
...我的if
语句应该怎么写?在对象中确定给定的键名是否存在的“正确”方法是什么?
var foo = room.exits[bar]
... foo是null吗?还是undefined? - drenlbar
不存在,room.exits[bar]
将返回undefined
。而'bar' in room.exits
则会返回false
。 - p.s.w.g