【问题标题】:How do I properly use prompts with if statements when creating a dialogue tree? [duplicate]创建对话树时如何正确使用带有 if 语句的提示? [复制]
【发布时间】:2015-12-29 00:37:40
【问题描述】:

我正在尝试创建一个带有分支答案系统的基本文字游戏。我马上就遇到了一个关于提示的问题。当我写下我的“if”语句以引发另一个提示时,什么也没有发生。我怎样才能解决这个问题?以下是我的工作示例:

confirm("You wake up to your mother's voice, 'Wake up! I can't believe you slept in this late! You need to get dressed and hurry on down to Professor Oak's Lab! No time for breakfast! Get going!'");

var questionOne = prompt("1. Hurry out of bed, quickly get dressed, and run out the door! 2. Roll out of bed sleepily, manage to put on your clothes, and make a cup of coffee before leaving the house. 3. Grumble back at your mother and go back to sleep." , "Enter 1, 2, or 3.");

if (questionOne === 1)
{
  prompt("You arrive at Professor Oak's lab in a rush, but haven't quite missed the event! It's time to get your first Pokemon! When you meet the Professor he says with a wink, 'Ah yes, it's you! I remember your mother quite well. Wonder woman... Alright, follow me!' You follow Oak into his lab to find 3 Pokeballs on his desk. 'Choose one,' he says with a hand gesture. [1. Left Pokeball. 2. Middle Pokeball. 3. Right Pokeball.]");
}

【问题讨论】:

  • 在if 的行上放一个断点。当它停在那里时,检查变量questionOne 的值。尝试在控制台中输入questionOne === 1 并记下结果。仔细思考为什么可能不满足条件;再次查看questionOne 并考虑其类型。

标签: javascript if-statement prompt


【解决方案1】:

prompt 函数返回一个字符串(因为您可以在其中添加任何想要的文本)。

因此,由于您使用的是 === 操作 - 而且它不会进行隐式转换 - 当您尝试将结果与 Number 进行比较时,if-statement 将永远不会通过。

您必须将比较更改为 == 运算符,这会进行隐式转换,或者您可以直接将其更改为字符串,例如 questionOne === '1'。看看下面的例子:

confirm("You wake up to your mother's voice, 'Wake up! I can't believe you slept in this late! You need to get dressed and hurry on down to Professor Oak's Lab! No time for breakfast! Get going!'");

var questionOne = prompt("1. Hurry out of bed, quickly get dressed, and run out the door! 2. Roll out of bed sleepily, manage to put on your clothes, and make a cup of coffee before leaving the house. 3. Grumble back at your mother and go back to sleep." , "Enter 1, 2, or 3.");

if (questionOne === '1')
{
  prompt("You arrive at Professor Oak's lab in a rush, but haven't quite missed the event! It's time to get your first Pokemon! When you meet the Professor he says with a wink, 'Ah yes, it's you! I remember your mother quite well. Wonder woman... Alright, follow me!' You follow Oak into his lab to find 3 Pokeballs on his desk. 'Choose one,' he says with a hand gesture. [1. Left Pokeball. 2. Middle Pokeball. 3. Right Pokeball.]");
}

【讨论】:

    【解决方案2】:

    提示返回一个字符串值。您需要将提示返回值转换为整数。或者反过来,比较字符串"1"。

    选项 1:

    if (parseInt(questionOne) === 1) {
      prompt("Second tree.")
    }
    

    选项 2:

    if (questionOne === '1') {
      prompt("Second tree.")
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      相关资源
      最近更新 更多