javascript - Get this Troll Program working
问题描述
Scenario :
- Attempted to create this troll 'guessing game program'.
- It prompts the user to guess a number between 1-10, and the user will get it wrong each time until they guess all numbers, frustrated, I tell them to guess one last time, upon this attempt, it says your answer was right!
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 :
Please correct this
or Suggest any better approach, i am open to options.
Thank You.
解决方案
一种选择是使用Set
1 到 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)
推荐阅读
- javascript - ReactJS:React-Router 将值传递到另一个页面
- javascript - 如何实现通用的反应原生背景?
- node.js - imageMagick 在套接字实例上失败
- state-machine - 用 2 个变量构建状态机
- javascript - 获取请求失败,状态为 403:snack.expo.io 上未定义
- python - 如何使用交互式图表将 jupyter notebook 导出为 html?
- php - PHP - htmlentities - 捷克语问题
- python-3.x - 我可以使用存储在 Docker 映像内的 GCS 存储桶中的 Python 模块吗?
- django - 翻译 django-allauth
- css - Bootstrap 是否默认添加水平间距?如果是这样,有没有办法覆盖这个设置?