【问题标题】:Modifying a variable in javascript? Not Working在javascript中修改变量?不工作
【发布时间】:2015-05-29 14:36:06
【问题描述】:

我正在努力做到这一点,当吃豆人遇到鬼魂时,他会失去生命。然后根据他的生命数显示一个特定的消息,但是变量似乎没有考虑到我正在改变它。

有什么建议吗?

var life=3;
// Lorsque l'on rencontre un fantome.
function manchePerdue()
{ 
  x_Pacman = 13;
  y_Pacman = 10;

  life = life-1;

  if (life=2) {
    window.alert("2 Lives Left");
  }
  else if (life=1) {
    window.alert("1 Life Left");
  }
  else { 
    window.alert("Game Over");
    gameover();
  }
}

【问题讨论】:

  • = 是赋值 == 是相等的,检查你的 if 语句。

标签: javascript variables global local pacman


【解决方案1】:

您需要在 if 中使用相等运算符 ==,而不是赋值运算符 =

if (life == 2) {
  alert("2 Lives Left");
else if (life == 1) {
  alert("1 Life Left");
} else {
  alert("Game Over");
  gameover();
}

使用= 意味着您要重新分配每个检查的值。例如:

var lives = 3;
if (lives = 1) {
  alert("1 life"); // Will show up
}
alert(lives); // Will show "1"!

Javascript 也有使用 === 运算符的严格相等的想法。在严格相等的情况下,类型也必须匹配。

1 == 1; // true
1 == "1"; // true
1 === "1"; // false

对于它的价值,您还会注意到您不需要写window.alert,只需写alert 就足够了,因为window 是全局范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2021-03-19
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多