JS 中常用的 Math 方法
1. 取最大值 和 取最小值
Math.min() 取一组数值的最小值
Math.max() 取一组数值的最大值
alert( Math.min(2,4,3,6,3,8,0,1,3) ); // 最小值 alert( Math.max(4,7,8,3,1,9,6,0,3,2) ); // 最大值
2. 舍入方法
Math.round() 标准舍入,会把数值四舍五入为最接近的整数
Math.ceil() 向上舍入,会把数值向上舍入为最接近的整数
Math.floor() 向下舍入,会把数值向下舍入为最接近的整数
3. 返回随机数
Math.random() 返回一个介于 0 到 1 的随机数,不包括 0 和 1
如果想大于这个范围的话,可以套用一下公式:
值 = Math.floor(Math.random() * 总数 + 第一个值)
alert( Math.floor(Math.random() * 10 + 5) ) // 5-14之间的任意数
4. 返回绝对值
Math.abs() 返回传入数值的绝对值
alert( Math.abs(12.34) ) // 返回 12.34 的绝对值 12