美文网首页
JS中的数学函数Math

JS中的数学函数Math

作者: 苏码码 | 来源:发表于2020-02-07 14:07 被阅读0次

JS中的数学函数Math
Math 称为数学函数,属于对象类型的函数

    typeof Math  // => "objec"
// 之所以叫做数学函数,是因为Math这个对象中提供了很多操作数字的方法
// Math中提供的常用方法
    // 1.abs:取绝对值
    Math.abs(-10)//  => 10
    // 如果传递的不是数字类型的值,先基于Number转换为数字类型再取绝对值
    console.log(Math.abs('-1')) // => 1
    console.log(math.abs('-1px')) // => NaN
    console.log(Math.abs(true)) // => 1

    // 2.Math.ceil / floor([number value])
    // 把一个数向上取整/向下取整
    console.log(Math.ceil(3.4)) //  =>4
    conslole.log(Math.ceil(-12.9)) // => -12
    console.log(Math.floor(3.9)) // => 3
    conslole.log(Math.floor(-12.1)) // => -13

   // 3. Math.round()
   // 四舍五入
   console.log(Math.round(2.4)) // => 2
   console.log(Math.round(2.5)) // => 3
   console.log(Math.round(2.9)) // => 3
   console.log(Math.round(-2.4)) // => -2
   console.log(Math.round(-2.5)) // => -2 负数中.5是要舍弃的
   console.log(Math.round(-2.9)) // => -4

    // 4. Math.max / min()
    // 获取一堆数中最大值和最小值
    console.log(Math.max(2,6,3,1)) // => 6
    console.log(Math.min(2,6,3,1)) // => 1
    // 如何获取数组中的最大值和最小值
    let arr = [3,1,6,8,10,2]
    console.log(Math.max(...arr)) // => 10
    console.log(Math.min(...arr)) // => 1

    // 5. Math.sqrt / pow()
    // sqrt: 开平方
    console.log(Math.sqrt(16)) // => 4
    console.log(Math.sqrt(-16)) // => NaN
    
    // pow:计算一个数的多少次幂
    console.log(Math.pow(3,2)) // => 9
    console.log(Math.pow(2,10)) // => 1024

    // 6.Math.random()
    // 获取0~1之间的随机小数
    console.log(Math.random())
    // 获取[m~n]之间的整数
    Math.round(Math.random()*(n-m) + m)
    // [1~100]
    console.log(Math.round(Math.random()*(99) + 1))

相关文章

网友评论

      本文标题:JS中的数学函数Math

      本文链接:https://www.haomeiwen.com/subject/brmmxhtx.html