美文网首页
Math常用方法

Math常用方法

作者: 追马的时间种草 | 来源:发表于2019-08-22 13:22 被阅读0次

Math:数学函数,并不是一个函数,而是一个对象 ,一下列举了一些较常用的Math方法及用法


  • Math.abs([number value]):获取绝对值
    如果传的不是数字,则会自动通过Number()转换再取绝对值
    console.log(Math.abs('-1'))//1
    console.log(Math.abd('1px'))//NAN
    console.log(Math.abs(true))//1
    
  • Math.ceil/floor([number value]):向上、向下取整
    向上取整一定是比原数大,(向下则相反)
    //Math.ceil()
         console.log(Math.ceil(12))//12
          console.log(Math.ceil(12.1))//13
          console.log(Math.ceil(12.7))//13
          console.log(Math.ceil(-12.1))//-12
          console.log(Math.ceil(-12.6))//-12
    //Math.floor()
          console.log(Math.floor(-12.1))//-13
          console.log(Math.floor(-12.6))//-13
    
  • Math.round():四舍五入
    无大小之分,在正数中.5进,负数中.5舍
         console.log(Math.round(12.4))//12
         console.log(Math.round(12.5))//13
         console.log(Math.round(-12.5))//12
         console.log(Math.round(-12.6))//13
    
  • Math.max/min([val1],[val2],…):取一堆数中的最大值最小值
  • Math.sqrt/pow()
    sprt:开平方
    pow(数值的几次幂)
    console.log(Math.pow(2,10))//1024
    
  • Math.random():随机数
    扩展:获取[n~m之间的随机数]
     Math.round(Math.random()*(m-n)+n)
    
    获取1-10之间的随机数
      Math.round(Math.random()*9+1)
    
    获取0-1之间的随机数
      Math.round(Math.random())
    
  • Math.PI
    Math.PI非函数,是一个数值

更多详情:Math方法

相关文章

网友评论

      本文标题:Math常用方法

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