如何在我的JavaScript程序中找到奇怪错误的原因?

时间:2017-06-06 01:19:45

标签: javascript

function wpnChs() {
  var p1 = prompt("Do you take a SWORD or a CLUB to battle?").toUpperCase();
  var HP = 1;
  var EHP = 1;
  var dmg = Math.floor(Math.random() * 1);
  var dmgT = Math.floor(Math.random() * 1);
  var first = Math.floor(Math.random() * 1);
  if (p1 === "SWORD") {
    HP = 10;
    EHP = 9;
    dmg = Math.floor(Math.random() * 8);
    dmgT = Math.floor(Math.random() * 6);
    first = Math.floor(Math.random() * 3);
  } else if (p1 === "CLUB") {
    HP = 11;
    EHP = 9;
    dmg = Math.floor(Math.random() * 6);
    dmgT = Math.floor(Math.random() * 5);
    first = Math.floor(Math.random() * 3);
  } else {
    wpnChs();
  }
}

function dmgD1() {
  EHP -= dmg;
}

function dmgD2() {
  HP -= dmgT;
}

function fR() {
  if (p1 === "SWORD") {
    dmg = Math.floor(Math.random() * 8);
    dmgT = Math.floor(Math.random() * 6);
    first = Math.floor(Math.random() * 3);
  } else {
    dmg = Math.floor(Math.random() * 6);
    dmgT = Math.floor(Math.random() * 5);
    first = Math.floor(Math.random() * 3);
  }
}

var fight = function() {
  if (first === 0 || 2) {
    dmgD1();
    if (dmg === 0) {
      alert("You attacked, but the enemy dodged it!");
      fR();
      fight();
    } else {
      alert("You attacked and did " + dmg + " damage. The enemy now has " + EHP
        +
        " health");
      if (EHP <= 0) {
        alert("You killed the enemy!")
      } else {
        fR();
        fight();
      }
    }
  } else {
    dmgD2();
    if (dmgT === 0) {
      alert("The enemy attacked, but you dodged it!");
      fR();
      fight();
    } else {
      alert("The enemy attacked and did " + dmgT + " damage. You now have " + HP
        +
        " health.");
      if (HP <= 0) {
        alert("You died!");
      } else {
        fR();
        fight();
      }
    }
  }
};

wpnChs();
fight();

1 个答案:

答案 0 :(得分:0)

好吧,第一个问题是范围问题。当它们仅作为第一个函数的作用域时,你试图在代码中使用在第一个函数中声明的变量。您可以通过几种不同的方式解决此问题。

  1. 您可以在功能之外声明它们,使它们更多 全球性的。
  2. 你仍然可以在当前函数中声明它们并传递 它们作为参数。喜欢战斗(第一,dmg); 我推荐这种方式。
  3. 我通过使用Chrome开发者工具发现了这个初始错误 - 在您浏览并尝试运行代码时尝试推送F-12,您经常会遇到控制台错误 - 如果有些事情无效则会出现以下情况。这些控制台错误通常可以提供对应用程序中发生的事情的宝贵见解。

    Error in the console

    请尝试阅读此内容,详细了解如何使用开发工具:https://developers.google.com/web/tools/chrome-devtools/javascript/

    我还建议您查看此处:https://www.w3schools.com/js/js_scope.asp以了解有关javascript中作用域的更多信息。

    坚持下去。第一步可能会让人感到有些困惑但是一旦你弄清楚它就会开始全部聚集在一起。