js--Math()

202 阅读1分钟
  1. Math.floor() / Math.ceil()

    总是返回数值的整数部分
    function ToInteger(x){
        x = Number(x)
        x < 0 ? Math.ceil(x) : Math.floor(x)
    }
    ToInteger(3.2) // 3
    ToInteger(3.5) // 3
    ToInteger(3.8) // 3
    ToInteger(-3.2) // -3
    ToInteger(-3.5) // -3
    ToInteger(-3.8) // -3
    
  2. Math.round()四舍五入

    Math.round(0.1) // 0
    Math.round(0.5) // 1
    Math.round(0.6) // 1
    
    // 等同于
    Math.floor(x + 0.5)
    注意,它对负数的处理(主要是对0.5的处理)。
    Math.round(-1.1) // -1
    Math.round(-1.5) // -1
    Math.round(-1.6) // -2
    
  3. Math.pow()

Math.pow方法返回以第一个参数为底数、第二个参数为幂的指数值。

// 等同于 2 ** 2
Math.pow(2, 2) // 4
// 等同于 2 ** 3
Math.pow(2, 3) // 8

下面是计算圆的面积

var radius = 20;
var area = Math.PI * Math.pow(radius, 2);
  1. Math.sqrt() 计算平方根

    Math.sqrt方法返回参数值的平方根。如果参数是一个负值,则返回NaN。

        Math.sqrt(4) // 2
        Math.sqrt(-4) // NaN