JavaScript快速入门笔记之八(Math对象、Date对象、Number对象、Boolean对象)
Math对象:
封装数学计算中常用的常量值,提供了常用的数学函数 不能被实例化
常用方法:
1.取整:Math.round(n) --对n四舍五入取整
Math.ceil(n) --上取整
Math.floor(n) --下取整
问题:Math.round()虽返回四舍五入的num类型,但只能取整
num.toFixed(n) 虽然可以按任意小数取数,但返回字符串类型,且有舍入误差
解决:自定义一个增强版round函数,即可返回指定位数四舍五入,又返回number类型数值,且没 有舍入误差。已放在在文件中。
2.随机数:Math.random() – 0<=num<1
0<=num<max : Math.random()*max
0<=num<max向下取整 : Math.floor(Math.random()max)
max~min范围取随机数:Math.floor(Math.random()(max-min+1)+min)
3.乘方/开方:
Math.pow(n,m): 计算n的m次方
Math.sqrt(n): 计算n的平方
获取最大值/最小值
Math.max(x1,x2,x3…)
Math.min(x1,x2,x3…)
扩展:通过Math.max获取数组的最大值
固定套路:
Math.max.apply(Math,arr);
apply: 在调用时,临时更换调用方法的对象
并将参数以数组形式传入
obj1.fun.apply(obj2,[p1,p2,p3…]);
Math.max.apply(Math,[p1,p2