1 基本使用
// 1 Math是一个内置对象 不是构造函数 直接使用就可以
2)常用的属性和方法
返回随机数
1)基本用法
//返回一个随机小数 x >= 0 x < 1; //没有参数 console.log(Math.random());
2)得到两数之间的一个随机整数
//得到一个两数之间的随机整数,包括两个数在内 //公式 Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 function getRandom(max,min) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(10,100)); //需要自己封装函数
3)随机点名
function getRandom(max,min) { return Math.floor(Math.random() * (max - min + 1)) + min; } var arr = [‘小王‘,‘小栗‘,‘小花‘,‘小牛‘,‘小黄‘]; console.log(arr[getRandom(0,arr.length -1)]);
5)猜字谜
//获取随机数函数 function getRandom(max,min) { return Math.floor(Math.random() * (max - min + 1)) + min; } var num = getRandom(1,10);//得到一个随机数 while (true) { //死循环 [ 后面必须有结束循环的 break ] var value = prompt(‘数字谜你来猜 1-10之间‘); if (value > num) { alert(‘猜大了‘); } else if (value < num) { alert(‘猜小了‘) } else { alert(‘猜对了‘); break; //退出整个循环 程序结束 } }
原文:https://www.cnblogs.com/fuyunlin/p/14407558.html