Math.random() 生成 [0,1) 的伪随机浮点数,常用于随机选择、洗牌等场景;通过 Math.floor(Math.random() * (max - min + 1)) + min 可生成指定范围的随机整数,如掷骰子、抽奖、随机选数组元素等。
JavaScript 的 Math.random() 方法用于生成一个大于等于 0 且小于 1 的伪随机浮点数。这个值可以用来实现各种随机功能,比如随机选择、洗牌、生成随机整数等。
调用 Math.random() 非常简单:
Math.random(); // 例如:0.456789返回的值范围是 [0, 1),意思是包括 0,但不包括 1。
实际开发中,我们通常需要的是某个整数范围内的随机数,比如掷骰子(1 到 6)。可以通过以下方式转换:
公式如下:
Math.floor(Math.random() * (max - min + 1)) + min;说明:
示例:生成 1 到 10 之间的随机整数
Math.floor(Math.random() * 10) + 1; // 结果:1 ~ 10这个方法在实际项目中非常实用:
取元素例如:从数组中随机选一项
const items = ['apple', 'banana', 'orange']; const randomItem = items[Math.floor(Math.random() * items.length)];基本上就这些。掌握 Math.random() 的使用和范围换算,就能应对大多数前端需要随机逻辑的场景了。