1、random
要生成 0-5 之间的随机整数
let random = Math.floor(Math.random() * 6);
这是因为 Math.random() * 6 可以生成 0-5.99999 之间的随机浮点数,Math.floor() 取整后变成 0-5 之间的整数。这里有一个完整例子:
js
for (let i = 0; i < 10; i++) {
let random = Math.floor(Math.random() * 6);
console.log(random);
}
// 可能输出:
// 3
// 1
// 4
// 0
// 2
// 5
// 1
// 3
// 0
// 2
Math.random() * (x - y + 1) + y 这个公式可以生成一个y到x之间的随机整数,更加均匀。
随机整数 = Math.floor(Math.random() * (最大值 - 最小值 + 1)) + 最小值
例如:生成一个0-5的随机整数
let random = Math.floor(Math.random() * (5 - 0 + 1) + 0);