1.1Math.max(),Math.min()
Math.max方法返回参数中最大的那个值,Math.min返回最小的那个值,如果参数为空,Math.min
返回Infinity
, Math.max
返回-Infinity
。
Math.max(2, -1, 5) // 5Math.min(2, -1, 5) // -1Math.min() // InfinityMath.max() // -Infinity复制代码
2.Math.floor(),Math.ceil()
Math.floor方法向下取整,Math.ceil方法向上取整
Math.floor
方法小于参数值的最大整数(地板值)。
Math.floor(3.2) // 3Math.floor(-3.2) // -4复制代码
Math.ceil
方法返回大于参数值的最小整数(天花板值)。
Math.ceil(3.2) // 4Math.ceil(-3.2) // -3复制代码
这两个方法可以结合起来,实现一个总是返回数值的整数部分的函数。
function ToInteger(x) { x = Number(x); return x < 0 ? Math.ceil(x) : Math.floor(x);}ToInteger(3.2) // 3ToInteger(3.5) // 3ToInteger(3.8) // 3ToInteger(-3.2) // -3ToInteger(-3.5) // -3ToInteger(-3.8) // -3复制代码
上面代码中,不管正数或负数,ToInteger
函数总是返回一个数值的整数部分。
3.Math.round()
Math.round方法用于四舍五入
Math.round(0.1) // 0Math.round(0.5) // 1Math.round(0.6) // 1// 等同于Math.floor(x + 0.5)复制代码
4.Math.random()
Math.random方法返回0-1之间的一个随机数,可能等于0,但一定小于1