gpt4 book ai didi

javascript - 关于变量、函数及其背后的逻辑的问题?

转载 作者:行者123 更新时间:2023-11-30 06:21:25 24 4
gpt4 key购买 nike

我来这里已经有一段时间了。

我正在学习有关 JavaScript 文本库冒险的教程。非常基础的教程。我有一个功能来改变房间。我理解它背后的逻辑并且它有效。

在我到达 goInside() 之前它不会给我错误;

property 'description' of undefined
at goInside (core.js:58)
at playerInput (core.js:94)
at HTMLDocument.<anonymous> (core.js:114)
at HTMLDocument.dispatch (jquery-3.2.1.min.js:3)
at HTMLDocument.q.handle (jquery-3.2.1.min.js:3)
goInside @ core.js:58
playerInput @ core.js:94
(anonymous) @ core.js:114
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3


function changeRoom(dir) {
if (rooms[currentRoom].directions[dir] !== undefined) {
currentRoom = rooms[currentRoom].directions[dir]
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p>You cannot go that way!</p>");
}
}

这是房间变量,我花了一分钟时间才理解格式。我添加了建筑物作为一个选项,它的作用就像方向一样。

var rooms = {
"start": {
"description": "You are in Town waiting for something to happen",

"details": "You notice a house and a shop. Should you explore?",

"directions": {
"north": "bridge",
"west": "clearing"
},

"buildings": {
"shop": "shop",
"house": "house"
},

"items": ["water", "stick"],

"minlvl": "1",
},

当前房间是开始的。您可以输入“向北走”。它会改变房间很好。但是,如果我想要超过 4 种不同的方式怎么办?我认为这可能有效,但无法弄清楚我具体哪里出错了。我重用了该函数但切换了元素。

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

不是找人为我编程,只是解释我可能缺少的逻辑。对于任何反馈,我们都表示感谢。谢谢。

编辑。

查看您的解决方案,我使用了 if 语句,但仍然收到以下错误。我不明白,因为 changeRooms 可以很好地显示描述,而 goInside 是 changeRooms 的副本。

Uncaught TypeError: Cannot read property 'description' of undefined
at goInside (core.js:58)
at playerInput (core.js:94)
at HTMLDocument.<anonymous> (core.js:114)
at HTMLDocument.dispatch (jquery-3.2.1.min.js:3)
at HTMLDocument.q.handle (jquery-3.2.1.min.js:3)
goInside @ core.js:58
playerInput @ core.js:94
(anonymous) @ core.js:114
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3

第 58 行

$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");

第 94 行是 goInside 函数

case "explore":

var building = input.split(" ")[1];
goInside(building);
break;

最佳答案

关于错误的最直接提示来自错误:Uncaught TypeError: Cannot read property 'description' of undefined。查看您尝试阅读 description 的位置:

 $('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");

因此,rooms[currentRoom] 返回 undefined。一种似是而非的解释是,如果您尝试输入例如“shop”,但没有定义 rooms['shop']。确保您有一个为“商店”定义的房间,即

rooms = {
"shop": {
// definition similar to "start" etc.
}
// ... the rest of the rooms
}

关于javascript - 关于变量、函数及其背后的逻辑的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com