【发布时间】:2023-03-12 01:56:01
【问题描述】:
我的问题是我不能使用超出其范围的变量。我正在尝试制作基于打字的游戏。它不会让我在 if 语句中使用变量“p2”。这不是完整的游戏,我需要知道如何在 if 语句中使用变量。我正在使用 JSfiddle。 HTML 代码只是一个运行该功能的按钮。 下面是 JavaScript 代码:
function input() {
var p = window.prompt("You wake up in a strange bed with a massive headache. There are two doors, one to the left, and one to the right. Which one would you like to go through?")
if (p == "left") {
var a1 = window.alert("You decided to go left. You walk up to what seems like another human. It was not. It tears you in half. You got the 'That ended fast' ending.")
if (p = "right") {
var p2 = window.prompt("You decided to go right. You look around and find a keycard! Two options: keep going straight or go left. Which direction would you like to go?")
}
if (p2 == "straight") {
}
}
}
【问题讨论】:
-
用
var声明的变量的范围是整个函数,而不仅仅是声明它的块。但是,这里的问题是,除非你到达内部if,否则你永远不会分配p2. -
第二个
if应该使用a1,而不是p。 -
如果您打算使用这样的嵌套
if语句来实现整个游戏,它将变得完全无法管理。您需要提出更结构化的设计,例如状态机。 -
如果只在
if语句中分配p2,为什么还要在if语句之外使用p2? -
我想使用
if之外的 p2,因为我可以根据您输入的内容添加另一个结尾或选择。
标签: javascript variables scope