繁体   English   中英

修改JavaScript中的变量? 无法运作

[英]Modifying a variable in javascript? Not Working

我试图做到这一点,以便当吃豆人遇到鬼魂时他会丧命。 然后根据生命的数量显示他有一条特定的消息,但是该变量似乎并未考虑到我正在对其进行更改。

有什么建议么?

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中使用等于运算符== ,而不是赋值运算符=

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是全局作用域。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM