在 JavaScript 中,您可以使用
Math.random()
函数生成随机数。
Math.random()
返回一个随机浮点数,范围从 0 到小于 1(包括 0 且不包括 1)
示例 1: 生成随机数
// generating a random number const a = Math.random(); console.log(a);
输出
0.5856407221615856
这里,我们声明了一个变量
a 并为其分配了一个大于或等于 0 且小于 1 的随机数。
注意: 在上面的程序中你可能会得到不同的输出,因为 Math.random() 会生成一个随机数。
我们可以使用范围(0,1) 中的这个值来使用公式找到任意两个数字之间的随机值:
Math.random() * (highestNumber-lowestNumber) + lowestNumber
示例 2: 获取 1 到 10 之间的随机数
// generating a random number const a = Math.random() * (10-1) + 1 console.log(`Random value between 1 and 10 is ${a}`);
输出
Random value between 1 and 10 is 7.392579122270686
这将显示一个大于 1 且小于 10 的随机浮点数。
以上所有示例都给出了浮点随机数。
您可以使用
Math.floor()
获取随机整数值。
Math.floor()
通过将值减小到最接近的整数值来返回数字。例如,
Math.floor(5.389); // 5 Math.floor(5.9); // 5
在两个数字之间找到随机整数值的语法:
Math.floor(Math.random() * (highestNumber-lowestNumber)) + lowestNumber
示例 3: 1 到 10 之间的整数值
// generating a random number const a = Math.floor(Math.random() * (10-1)) + 1; console.log(`Random value between 1 and 10 is ${a}`);
输出
Random value between 1 and 10 is 2
这将显示1(包含)到10(不包含)之间的整数输出,即(1到9)。此处,
Math.floor()
用于将十进制值转换为整数值。
同样,如果你想在
min(含)到
max(含)之间找到随机整数,你可以使用以下公式:
Math.floor(Math.random() * (max-min + 1)) + min
示例 4: 两个数字之间的整数值(含)
// input from the user const min = parseInt(prompt("Enter a min value: ")); const max = parseInt(prompt("Enter a max value: ")); // generating a random number const a = Math.floor(Math.random() * (max-min + 1)) + min; // display a random number console.log(`Random value between ${min} and ${max} is ${a}`);
输出
Enter a min value: 1 Enter a max value: 50 Random value between 1 and 50 is 47
这将显示min(含)到max(含)之间的整数输出。