您的购物车目前是空的!
前端 JS 如何生成随机数?
Math.random()
方法返回一个范围在 0(包括)到 1(不包括)之间的伪随机浮点数。
要生成一个指定范围内的随机整数,你可以结合 Math.random()
方法和一些数学运算来实现。以下是一个生成指定范围内随机整数的示例:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 生成 1 到 10 之间的随机整数
const randomInt = getRandomInt(1, 10);
console.log(randomInt);
上述代码中的 getRandomInt()
函数接受一个最小值 min
和一个最大值 max
,并返回一个在这个范围内的随机整数。Math.floor()
方法用于向下取整,确保结果是整数。
发表回复