JS中Math函數的常用方法


Math 是數學函數,但又屬於對象數據類型 typeof Math => ‘object’ 
console.dir(Math) 查看Math的所有函數方法。 
1,Math.abs() 獲取絕對值

Math.abs(-12) = 12

2,Math.ceil() and Math.floor() 向上取整和向下取整

 console.log(Math.ceil(12.03));//13
 console.log(Math.ceil(12.92));//13
 console.log(Math.floor(12.3));//12
 console.log(Math.floor(12.9));//12

 

3,Math.round() 四舍五入 
注意:正數時,包含5是向上取整,負數時包含5是向下取整。

1、Math.round(-16.3) = -16
2、Math.round(-16.5) = -16
3、Math.round(-16.51) = -17

4,Math.random() 取[0,1)的隨機小數 
案例1:獲取[0,10]的隨機整數

console.log(parseInt(Math.random()*10));//未包含10
console.log(parseInt(Math.random()*10+1));//包含10

案例2:獲取[n,m]之間的隨機整數

Math.round(Math.random()*(m-n)+n)

5,Math.max() and Max.min() 獲取一組數據中的最大值和最小值

console.log(Math.max(10,1,9,100,200,45,78));
console.log(Math.min(10,1,9,100,200,45,78));

6,Math.PI 獲取圓周率π 的值

console.log(Math.PI);

7,Math.pow() and Math.sqrt() 

Math.pow()獲取一個值的多少次冪 
Math.sqrt()對數值開方

1.Math.pow(10,2) = 100;
2.Math.sqrt(100) = 10;

 

//例子:自己定義一個對象,實現系統的max的方法
    function Mymax() {
      //添加了一個方法
      this.getMax = function () {
        //假設這個數是最大值
        var max = arguments[0];
        for (var i = 0; i < arguments.length; i++) {
          if (max < arguments[i]) {
            max = arguments[i];
          }
        }
        return max;
      };
    }
    // 實例對象
    var my = new Mymax();
    console.log(my.getMax(9, 5, 6, 32));
    console.log(Math.max(9, 5, 6, 32));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM