Math 是 JavaScript 的原生对象,提供各种数学功能。
该对象不是构造函数,不能生成实例,所有的属性和方法都必须在 Math 对象上调用。
// console.log(Math); // {} 它里面有很多的属性和方法,针对数学计算的
console.log(Math.floor(3.999)); // 3 向下取整 去掉小数部分
console.log(Math.ceil(3.001)); // 4 向上取整 只要有小数就进位
console.log(Math.round(3.14159)); // 3 四舍五入
console.log(Math.abs(-100)); // 100 绝对值
console.log(Math.max(1, 2, 36, 9)); // 36 取参数的最大值
console.log(Math.min(1, 2, 36, 9)); // 1 取参数的最小值
console.log(Math.pow(2, 10)); // 1024 2的10次方
console.log(Math.pow(3, 2)); // 9 3的平方
console.log(Math.sqrt(60)); // 7-8 开根号
随机数
随机数:大于等于0小于1的一个数
for (var i = 0; i < 20; i++) {
console.log(Math.random());
}
公式
1、大减小加1
2、乘以随机数
3、加上最小数
4、向下取整
// 随机数公式
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (var i = 0; i < 20; i++) {
console.log(getRandom(10, 100));
}
案例:抽奖、验证码~