Math对象的方法

439 阅读1分钟

幂和开方:Math.pow()、Math.sqrt()

向上取整和向下取整:Math.ceil()、Math.floor()

Math.round()

可以将一个数字四舍五入为整数
    <script>
        console.log(Math.round(3.4));  //3
        console.log(Math.round(3.5));  //4
        console.log(Math.round(3.98));  //4
        console.log(Math.round(3.49));  //3
    </script>

image.png

         var a = 2.6548;
        console.log(Math.round(a*100)/100); //2.65
Math.max()和Math.min()

Math.max()可以得到参数列表的最大值

Math.min()可以得到参数列表的最小值

         console.log(Math.max(6,2,9,3));  //9
        console.log(Math.min(6,2,9,3));   //2

利用Math.max()求数组最大值

Math.max()要求参数必须是“罗列出来”,而不能是数组

apply方法可以指定上下文,并且以数组的形式传入“零散值”当做函数的参数

         var  arr = [3,6,9,2];
        var max = Math.max.apply(null,arr);
        console.log(max);  //9
        
          // 在ES6中求数组最大值可以以下写法
        console.log(Math.max(...arr));  //9

随机数Math.random()

Math.random()可以得到0~1之间的小数

为了得到[a,b]区间内的整数,可以使用公式: parseInt(Math.random()*(b-a+1))+a

        // 如果要生成[a,b]之内的整数,就要使用公式parseInt(Math.random()*(b-a+1))+a
        // [3,8]
        console.log(parseInt(Math.random()*(8-3+1))+3);