5> Math对象常用方法

77 阅读1分钟

min()和max()

用来确定数组中的最大值和最小值,使用扩展操作符

let arr = [23 ,45, 2, 43, 32, 87]
console.log(Math.min(...arr))      // 2
console.log(Math.max(...arr))      // 87

ceil(), floor(), round()

Math.ceil() // 向上取整 Math.floor() // 向下取整 Math.round() // 四舍五入

console.log(Math.ceil(20.1))      // 21
console.log(Math.floor(20.9))      // 20
console.log(Math.round(20.5))      // 21
console.log(Math.round(20.4))      // 20

random()

返回0-1内的随机数,包含0但是不包含1 如果要求两个数字蹭的随机数,就要 随机数 * 最大值 - 最小值 + 1 + 最小值

求 5 - 20 内的随机数
let num = Math.random() * (20 - 5 + 1) + 5  

abs()

取绝对值

console.log(Math.abs(5))       // 5
console.log(Math.abs(-5))      // 5