如果语句 JavaScript,数学在我的 else 语句中不起作用,我做错了什么?

这个问题很简单。我正在制作一个猜数字游戏,现在我正在为我的游戏添加一个尝试功能。每次失败的尝试都应将 1 添加到我的attempts变量中:


var numberwang = Math.floor(Math.random() * 6);

var attempts = 0;


console.log(numberwang);

console.log(attempts);


document.getElementById("guessbutton").onclick = function(e) {

  e.preventDefault();


  if (document.getElementById("guess").value == numberwang) {


    alert("That's numberwang!");

    attempts = 0;

    console.log("Attempts:",attempts)

  } else {


    alert("That's not numberwang, try again");

    attempts = attempts + 1;

    console.log("Attempts:",attempts)

  }


}

<p>Guess a number</p>

<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>

但是 else 语句参数不起作用。每次尝试都不会向我的尝试变量添加任何内容。任何人都可以看到有什么问题吗?提前致谢。


注意:else语句不适用于任何数学运算。


子衿沉夜
浏览 134回答 2
2回答

largeQ

您的问题是,当您使用var关键字时,您正在创建一个新变量。您应该删除varif 和 else的内部。这将允许您更改外部attempts变量,而不是您使用var.var numberwang = Math.floor(Math.random() * 6);var attempts = 0;document.getElementById("guessbutton").onclick = function(e) {&nbsp; e.preventDefault();&nbsp; if (document.getElementById("guess").value == numberwang) {&nbsp; &nbsp; alert("That's numberwang!");&nbsp; &nbsp; attempts = 0;&nbsp; } else {&nbsp; &nbsp; alert("That's not numberwang, try again");&nbsp; &nbsp; attempts = attempts + 1;&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp; console.log("Attempts is: "+attempts);}<p>Guess a number</p><form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>我想我明白你有什么问题。您期望已记录到控制台的内容在变量更改时发生更改。事情不是这样的console.log。它只记录变量的当前值。如果您想查看新值,您应该再次记录它,在这种情况下,在每次猜测之后。

ITMISS

每次单击时,您都在定义一个变量。从 if/else 块中删除“var”<p>Guess a number</p><form><input type="text" id="guess"><button id="guessbutton">Guess</button></form><script type="text/javascript">&nbsp; &nbsp; var numberwang = Math.floor(Math.random() * 6);&nbsp; &nbsp; var attempts = 0;&nbsp; &nbsp; console.log(numberwang);&nbsp; &nbsp; console.log(attempts);&nbsp; &nbsp; document.getElementById("guessbutton").onclick = function(e) {&nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; if (document.getElementById("guess").value == numberwang) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("That's numberwang!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; attempts = 0;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("That's not numberwang, try again");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; attempts = attempts + 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript