Math 对象

Math 对象的属性

math.E 自然对数的底数,即常量 e 的值;
Math.LN10 10 的自然对数;
Math.LN2 2 的自然对数;
Math.LOG2E 以 2 为底 e 的对数;
Math.LOG10E 以 10 为底 e 的对数;
Math.PI π的值;
Math.SQRT1_2 1/2的平方根(2的平方根的倒数);
Math.SQRT2 2的平方根;

min() 和 max() 方法

Math.min() 一组数值中的最小值;
Math.max() 一组数值中的最大值;

例子

var max = Math.max(3 , 54 , 32 , 16) ;
alert (max);        //54

四舍五入

Math.ceil() 执行向上舍入, 即它总是将数值向上舍入为最接近的整数;
Math.floor() 执行向下舍入
Math.round() 执行标准舍入,即四舍五入

例子

        alert(Math.ceil(25.9));     //26
        alert(Math.ceil(25.5));     //26
        alert(Math.ceil(25.1));     //26

        alert(Math.round(25.9));    //26
        alert(Math.round(25.5));    //26
        alert(Math.round(25.1));    //25

        alert(Math.floor(25.9));    //25
        alert(Math.floor(25.5));    //25
        alert(Math.floor(25.1));    //25

random() 方法

Math.random() 返回大于0 ,小于1 的一个随机数

例子

值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值 )

var num = Math.floor(Math.random() * 10 + 1);        //1到10之间的随机数

var num = Math.floor(Math.random() * 9 + 2);        //2到10之间的随机数

随机取值函数

        function selectFrom(lowerValue, upperValue) {
            var choices = upperValue - lowerValue + 1;
            return Math.floor(Math.random() * choices + lowerValue);
        }

        var num = selectFrom(2, 10);
        alert(num);   //number between 2 and 10 (inclusive)

        var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
        var color = colors[selectFrom(0, colors.length-1)];
        alert(color);  //any of the strings in the array

其它方法

Math.abs(num) 返回 num 的绝对值
Math.exp(num) 返回 Math.E 的 num 次幂
Math.log(num) 返回 num 的自然对数
Math.pow(num,power) 返回 num 的 power 次幂
Math.sqrt(num) 返回 num 的平方根
Math.acos(x) 返回 x 的反余弦值
Math.asin(x) 返回 x 的反正弦值
Math.atan(x) 返回 x 的反正切值
Math.cos(x) 返回 x 的余弦值
Math.sin(x) 返回 x 的正弦值
Math.tan(x) 返回 x 的正切值

posted @ 2017-11-24 15:16  多弗朗小明  阅读(151)  评论(0编辑  收藏  举报