在 JavaScript 中,你可以使用 Math.random()
函数来获取一个随机数。这个函数返回介于 0(包含)和 1(不包含)之间的浮点数。
以下是一些使用 Math.random()
来获取随机数的常见用法:
获取介于 0 和 1 之间的随机浮点数:
const randomNumber = Math.random();
console.log(randomNumber);
获取指定范围内的随机整数(例如 0 到 10 之间的随机整数):
const min = 0;
const max = 10;
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomNumber);
在这个示例中,使用 Math.random()
乘以范围的大小(max - min + 1
),然后再加上最小值(min
),最后使用 Math.floor()
函数将结果向下取整,得到一个范围内的整数。
获取指定范围内的随机浮点数(例如 10 到 20 之间的随机浮点数):
const min = 10;
const max = 20;
const randomNumber = Math.random() * (max - min + 1) + min;
console.log(randomNumber);
这些是一些常见的使用 Math.random()
函数来获取随机数的方法。你可以根据自己的需求调整范围和用法。