在JavaScript中生成1到3之间的随机整数,可以使用Math.random()
函数结合Math.floor()
函数来实现。以下是具体的实现方法:
function getRandomInt(min, max) {
min = Math.ceil(min); // 向上取整
max = Math.floor(max); // 向下取整
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomNum = getRandomInt(1, 3);
console.log(randomNum); // 输出1、2或3中的一个
(max - min + 1)
之间的随机小数。(max - min)
之间的整数。min
到max
之间。Math.random() * (max - min) + min
并取整,可能会导致某些数字出现的概率不均匀。通过使用Math.floor(Math.random() * (max - min + 1)) + min
可以确保每个数字出现的概率相等。通过上述方法,你可以确保生成的随机数在1到3之间,并且每个数字出现的概率是相等的。
领取专属 10元无门槛券
手把手带您无忧上云