Javascript 关于变量、函数及其背后的逻辑的问题?
我已经有一段时间没来这里了 下面是关于JavaScript文本库冒险的教程。非常基础的教程。我有换房间的功能。我理解它背后的逻辑,它是有效的 在我到达goInside()之前,它不会给我错误 当前房间已启动。你可以输入“往北走”。它会很好地改变房间。但是如果我想要4种以上的方式呢?我原以为这可能行得通,但无法明确指出我哪里出了错。我重新使用了这个函数,但把元素换掉了Javascript 关于变量、函数及其背后的逻辑的问题?,javascript,function,object,variables,Javascript,Function,Object,Variables,我已经有一段时间没来这里了 下面是关于JavaScript文本库冒险的教程。非常基础的教程。我有换房间的功能。我理解它背后的逻辑,它是有效的 在我到达goInside()之前,它不会给我错误 当前房间已启动。你可以输入“往北走”。它会很好地改变房间。但是如果我想要4种以上的方式呢?我原以为这可能行得通,但无法明确指出我哪里出了错。我重新使用了这个函数,但把元素换掉了 function goInside(building) { if (rooms[currentRoom].building
function goInside(building) {
if (rooms[currentRoom].buildings[building] !== undefined) {
currentRoom = rooms[currentRoom].buildings[building],
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p>You cannot go that way!</p>");
}
}
确保所有房间都有
建筑物
属性。如果没有其他建筑物可以从该房间进入,则该物业应为空对象,例如:
"buildings": {},
否则,尝试访问房间[currentRoom].buildings[building]
时会出错。即使您正在测试是否定义了它,但如果没有对象可以开始,它也无法使用[building]
索引对象
或者您需要先对此进行goInside()
函数检查
function goInside(building) {
if (rooms[currentRoom].buildings && rooms[currentRoom].buildings[building]) {
currentRoom = rooms[currentRoom].buildings[building],
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p>You cannot go that way!</p>");
}
}
功能区(建筑){
if(房间[currentRoom]。建筑物和房间[currentRoom]。建筑物[building]){
currentRoom=房间[currentRoom]。建筑物[building],
$(“#游戏文本”)。追加(“”+房间[currentRoom]。说明+””;
}否则{
$(“#游戏文本”)。追加(你不能那样做!”;
}
}
关于错误的最直接的提示来自错误:未捕获类型错误:无法读取未定义的属性“说明”
。查看您尝试阅读的位置说明
:
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
代码看起来不错,有什么问题吗?您是否有名为
shop
和house
的房间?currentRoom
必须是rooms
对象中的属性。我有这些房间以及其他地图。我收到这个错误[code]core.js:58 Uncaught TypeError:Cannot Read你所有的房间都有buildings
属性吗?请在问题中添加完整的错误信息,而不是评论。
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
case "explore":
var building = input.split(" ")[1];
goInside(building);
break;
"buildings": {},
function goInside(building) {
if (rooms[currentRoom].buildings && rooms[currentRoom].buildings[building]) {
currentRoom = rooms[currentRoom].buildings[building],
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p>You cannot go that way!</p>");
}
}
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
rooms = {
"shop": {
// definition similar to "start" etc.
}
// ... the rest of the rooms
}