示例: 猜数字的程序
// program where the user has to guess a number generated by a program function guessNumber() { // generating a random integer from 1 to 10 const random = Math.floor(Math.random() * 10) + 1; // take input from the user let number = parseInt(prompt('Guess a number from 1 to 10: ')); // take the input until the guess is correct while(number !== random) { number = parseInt(prompt('Guess a number from 1 to 10: ')); } // check if the guess is correct if(number == random) { console.log('You guessed the correct number.'); } } // call the function guessNumber();
输出
Guess a number from 1 to 10: 1 Guess a number from 1 to 10: 8 Guess a number from 1 to 10: 5 Guess a number from 1 to 10: 4 You guessed the correct number.
注意: 每次运行程序你会得到不同的输出值,因为每次产生不同的数字。
在上面的程序中,创建了
guessNumber()
函数,其中使用
生成了从 1 到 10 的随机数Math.random()
函数。
要了解有关如何生成随机数的更多信息,请访问 JavaScript 生成随机数。
系统会提示用户猜测一个从 1 到 10 的数字。
parseInt()
将数字字符串值转换为整数值。
while
循环用于接收用户的输入,直到用户猜出正确答案。
if...else
语句用于检查条件。等于 ==
运算符用于检查猜测是否正确。
if(number == random)
要了解有关比较运算符的更多信息,请访问 JavaScript 比较运算符。