【问题标题】:How do I use a variable out of its scope如何使用超出其范围的变量
【发布时间】: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


【解决方案1】:

在根作用域(当前函数)中声明您的 var,这样它们就可以在任何子作用域(if 语句)中访问。这是示例,我已经稍微纠正了您的逻辑,仅用于示例案例。

function input() {
  // Set variables
  let p, a1, p2;
  
  // Do your logic
  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") {
    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") {
    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?")
  }
  // Check p2
  if(p2 == "straight") {
      alert("Yes we go straight!");
  }
}

// Run fn
input();

【讨论】:

  • 哦,好吧,我在想,如果我将变量放在函数的括号或类似的东西中,它会起作用。
猜你喜欢
  • 2013-10-26
  • 2020-06-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多