JavaScript 生成0-9 随机整数 - 使用 Math.random() 和 Math.floor()
要生成 0-9 的随机整数,可以使用 Math.random() 方法与 Math.floor() 方法结合使用。
Math.random() 方法返回一个大于等于 0 且小于 1 的随机浮点数。通过将其乘以 10,可以得到一个大于等于 0 且小于 10 的随机浮点数。
然后,使用 Math.floor() 方法将该随机浮点数向下取整,得到一个大于等于 0 且小于 10 的随机整数。最后,取余 10,就可以得到一个 0-9 的随机整数。
以下是一个生成 0-9 的随机整数的示例代码:
let randomInt = Math.floor(Math.random() * 10);
console.log(randomInt);
每次运行这段代码,都会输出一个 0-9 之间的随机整数。
原文地址: https://www.cveoy.top/t/topic/pK9s 著作权归作者所有。请勿转载和采集!