Math.random()
返回一个随机的小数 0 =< x < 1 [0,1)
console.log(Math.random());//这个方法里面不跟参数
如何用 Math.random() 来进行随机点名?
获取指定范围内的随机整数:这是个固定写法,大家不需要记忆,知道怎么用即可。
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
//传入1,,10,过程如下:
//Math.floor( 0 =< x < 1 * (max - min + 1) ) + min;
//Math.floor( 0 =< x < 1 * 10 ) + min;
//Math.floor( 0 =< x < 10 ) + min; // 这个是带小数的范围
// 0 =< x < 10 + 1; // 取过floor之后就是整数
// 1 =< x < 11 // [1,10]
}
案例:随机点名
<script>
var arr = ['张三', '李四', '王五', '赵六', '韩立', '王林'];
// console.log(arr[0]);
// arr 调用getRandom这个函数
console.log(arr[getRandom(0, arr.length - 1)]);
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>