函数在JavaScript中重复n次

Function repeats n times in JavaScript

本文关键字:JavaScript 函数      更新时间:2023-09-26

我如何编辑这个代码,我可以设置一个数字,你有多少机会猜测正确的数字?现在,如果我想给一个额外的机会,我必须设置新的IF。

<html>
<head>
<title> Spek skaiciu! </title>
</head>
<body>
<style>
.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}
.blokas
{
    display:inline;
}
</style>
<script type="text/javascript">
var kiek = 0;
function zaisk() {
kiek = kiek + 1;
document.getElementById("kiek").innerHTML=kiek;
var sk = Math.floor(Math.random()*10)+1;
var spejimas=prompt("Atspėk kokių skaičių sugalvojau, nuo 1 iki 10. Turi du spėjimus!");

if (spejimas==sk)
{
alert("Atspėjai! Skaičius buvo: " +sk);
}
else if (spejimas<sk)
{
var antspejimas=prompt("Neteisingai! Skaičius didesnis už: " +spejimas);
}
else if (spejimas>sk)
{
var antspejimas=prompt("Neteisingai! Skaičius mažesnis už: " +spejimas);
}

//Antras spejimas /*
if (antspejimas==sk)
{
alert("Antru spėjimu atspėjai! Skaičius buvo: " +sk);
}
else if (antspejimas<sk)
{
alert("Deja, jums nepavyko atspėti. Spauskite mygtuką jei norite žaisti dar kartą");
}
else if (antspejimas>sk)
{
alert("Deja, jums nepavyko atspėti. Spauskite mygtuką jei norite žaisti dar kartą");
}
document.getElementById("koks").innerHTML=sk;
}
</script>
<center>
<br />
<br />
<br />
<br />
<br />
<button class="button" onClick="zaisk()">Pradėti žaidimą!</button> <br>
<br> Šį žaidimą žaidiai jau: <b><h2>
<div id="kiek">
0
</div></b></h2>
kartus(-ų)! <br> <br>
Paskutinis teisingas skaičius buvo:
<div id="koks" class="blokas">
0
</div></b></h2>
</center>
</body>
</html>

这是一个完美的while循环场景!

var correct_answer = 7; // Any correct answer condition
var max_num_of_guesses = 5; // Set number of guesses you want to allow user
var num_guesses = 0; // This will be the counter
var answer;
while (num_guesses <= max_num_of_guesses) {
  answer = prompt("Guess a number.");
  num_guesses++; // Increment guesses
  if (answer > correct_answer) { 
    alert("Guess lower.")
  } else if (answer < correct_answer) {
    alert("Guess higher.");
  } else {
    break; // Guess was correct. Exit the while loop
  }
}
// If now out of the loop, you've either broken out because of a successful guess, or the user never guess it correctly
if (answer === correct_answer) {
  alert("Correct! The number was " + correct_answer)
} else {
  alert("Sorry, that was too many guesses! The number was " + correct_answer)
}