·Math对象
值得注意的一点,与其他全局对象不同的是,Math不是一个构造器。Math的所有属性和方法都是静态的。(非构造函数)
静态变量——指的是在程序执行前系统就已经给这个变量分配了一定的存储空间,在运行时也不再改变分配情况
1.绝对值方法
console.log(Math.abs(1));//1
console.log(Math.abs(-1));//1
console.log(Math.abs('-1'));//1 隐式转换 会把字符型转换为数字型
console.log(Math.abs('pinl'));//NaN
2.三个取整方法
//(1)Math.floor() 向下取整 往小的取
console.log(Math.floor(1.1));//1
console.log(Math.floor(1.9));//2
//(2)Math.ceil() 向上取整 往大的取
console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.9));//2
//(3)Math.round 四舍五入
console.log(Math.round(1.4));//1
console.log(Math.round(2.6))//3
3.随机数方法 random()
作用:随机生成一个[0,1)内的浮点数
得到一个两数之间的随机整数*(抽奖案例)*
function getRandomInt(min,max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}
那么如果也要取到最大值呢?
我们想要得到两个数之间的随机整数 并且 包含这两个整数
function getRandomInt(){
return Math.floor(Math.random()*(max - min + 1) + min;
随机点名案例
function getRandomInt(){
return Math.floor(Math.random()*(max-min+1)+min;
}
var arr = ['张三','小明','李四','小欧','小华'];
console.log(arr[Math.getRandomInt(0,arr.length-1)]);