JavaScript之Math对象

178 阅读1分钟

Math

Math 是一个内置对象, 它具有数学常数和函数的属性和方法。不是一个函数对象。

基本方法

    Math.round() // 四舍五入。

  Math.ceil() // 向上取整,有小数 整数部分就加1 

  Math.floor() // 向下取整 

  Math.abs() // 返回绝对值;

  Math.max() // 返回一堆数中最大值

  Math.min() // 返回一堆数中最小值
    
   Math.random() // 方法返回介于0到1之间一个随机数,不包括1(包前不包后)

   Math.PI // 圆周率 3.141592653589793

数组中最大值/最小值

var arr = [2, 3, 20, 10, 8, 1]  
Math.max.apply(null, arr) // 20 返回数组的最大值;
Math.min.apply(null, arr) // 1 返回数组的最大值;
Math.max(...arr)
Math.min(...arr)

随机小数

// [0, 1} 随机小数
Math.random()

// [n, m) 随机小数
Math.random() * (m - n) + n

生成随机整数

Math.round(Math.random() * (max - min)) + min

// 0~10
Math.round(Math.random() * 10)
// 10~30
Math.round(Math.random()*(30-10) + 10)

生成从0~100随机整数

Math.round(Math.random() * 100)

----------------------------------------------------------------------------------------------------------------
参考文章&&强烈推荐:布罗利