Math.random() 方法:生成随机数
方法定义:生成 [0, 1) 之间的随机浮点数。
直接上代码:
/*
* 生成两个整数之间的随机整数,并且要包含这两个整数
*/
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandom(1, 10));
生成 [0, x) 之间的随机数
Math.round(Math.random()*x)
根据上面的例子,我们还可以再延伸一下,来看看随机点名的例子。
/*
* 生成两个整数之间的随机整数,并且要包含这两个整数
*/
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const arr = ['许嵩', '邓紫棋', '毛不易', '解忧邵帅'];
const index = getRandom(0, arr.length - 1); // 生成随机的index
console.log(arr[index]); // 随机点名