Math.floor(): 向下取整,往最小取值
console.log(Math.floor(5.9));
运行代码:
Math.ceil():往最大取值,向上取整
console.log(Math.ceil(1.002));
运行代码:
Math.random() 对象随机数方法 random()返回一个随机的小数 伪随机数在范围从0到小于1
获取1-10之间随机整数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
console.log(getRandom(1,10));
运行结果:
案例:随机点名
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
var abs=['张三','李四','王二','麻子']
console.log(abs[getRandom(0,3)]);
案例:猜数字游戏
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
var abs=getRandom(1,10);
while (true) {
var num=prompt('请输入1-10之间的数字')
if(num>abs){
alert('你猜大了');
}else if(num<abs){
alert('你猜小了');
}else{
alert('你猜对了');
break;//退出整个循环
}
}
总结Math对象就是一个常数和函数的属性和方法,不是一个函数对象,可以直接使用。