Math是一个内置对象,它具有数学常数和函数的属性和方法,不是一个函数对象
描述
Math数学对象,不是一个构造函数,所以不需要用new来调用,而是直接使用里面的属性和方法即可
console.log(Math.PI);//3.141592653589793
方法
1.Math.max( )
Math.max() 函数返回一组数中的最大值。
语法
Math.max(value1[,value2, ...])
参数为一组你需要比较的数值,返回给定的一组数字中的最大值。如果给定的参数中至少有一个参数无法被转换成数字,则会返回 NaN,如果没有参数,则返回 -Infinity
console.log(Math.max(1, 7, 12));//12
console.log(Math.max(1, 5 ,'卡卡西'));//NaN
console.log(Math.max());//-Infinity
Math.min( ) 同理
2.Math.abs( )
Math.abs( )函数返回参数的绝对值
console.log(Math.abs(-21));//21
console.log(Math.abs(32));//32
console.log(Math.abs('-1'));//1 隐式转换,会把字符串型-1转换为数字型
console.log(Math.abs('卡卡西'));//NaN无法被转换成数字,则会返回NaN
3.三个取整方法
Math.floor( )向下取整,忽略小数点及其后面的数字
console.log(Math.floor(3.8));//3
console.log(Math.floor(3.1));//3
Math.ceil( ) 向上取整,遇见小数点,小数点前的数字加1
console.log(Math.ceil(3.8));//4
console.log(Math.ceil(3.1));//4
Math.round( ) 四舍五入
console.log(Math.round(3.8));//4
console.log(Math.round(3.1));//3
Math.round( )中,.5特殊,它往大了取
console.log(Math.round(1.5));//2
console.log(Math.round(-1.5))//-1
**4.Math.random( )随机数方法
random( )返回一个随机的浮点数,取值范围为 [0,1),这个方法里面不跟参数
console.log(Math.random());
得到一个两数之间的随机整数,包含两个数在内
function getRandom(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
利用随机数实现随机点名
var arr = ['卡卡西', '漩涡鸣人', '宇智波佐助', '春野樱'];
function getRandom(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min
}
console.log(arr[getRandom(0, arr.length-1)]);
案例:猜数字游戏
随机生成一个1~10之间的数字,并让用户输入一个数字
1.大于该数字,提示,数字大了,请继续;
2.小于该数字,提示,数字小了,请继续;
3.等于该数字,提示,恭喜你,猜对了。
4.只有3次机会
function getRandom(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}//得到一个两数之间的随机整数,包含两个数在内
var random = getRandom(0,10);//随机生成一个1~10之间的数字
for (var i = 0; i < 3; i++){//只有3次机会,循环3次
var num = prompt('请输入1~10之间的数字');
if(num > random){
alert('你猜大了');
}else if(num < random){
alert('你猜小了')
}else{
alert('恭喜你,猜对了')
break;
}
}