首页 > 解决方案 > Get this Troll Program working

问题描述

Scenario :

Code - I am new at JS so I have not really gone into DOM manipulation and the code for some reason does not work.

    <!DOCTYPE html>
<html>
<head>
    <title>Guessing Game</title>
</head>
<body>

<script type="text/javascript">
    var numset = 0;
    var guess = numset + 1;
    var max = numset >= 11;

    while (guess !== max) {
        prompt("I am guessing a number between 1-10, let's see if you can guess it!"); 

    } else {
        alert("You Won! Number of guesses: 11")
    }



</script>

</body>
</html>

Todo :

Thank You.

标签: javascriptjqueryhtmlcss

解决方案


一种选择是使用Set1 到 10 之间的数字,提示输入一个数字并将其从集合中删除,直到集合为空,然后显示猜测的总数。

请注意,由于程序使用prompt,它将阻止用户的浏览器 - 如果可能的话,请考虑使用对用户不太友好的东西,例如input和按钮/输入侦听器。

// Set of numbers from 1 to 10:
const numSet = new Set(Array.from(
  { length: 10 },
  (_, i) => i + 1
));
let guesses = 1; // to account for the final guess at the end
while(numSet.size > 0) {
  const guessed = prompt("I am guessing a number between 1-10, let's see if you can guess it!");
  numSet.delete(Number(guessed));
  guesses++;
}
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
alert("You Won! Number of guesses: " + guesses)


推荐阅读