JavaScript的内置对象之Math对象

一、Math对象概述:

  Math(算数)对象的作用是:执行常见的算数任务。保存数学公式和信息.

  与我们在JavaScript 直接编写计算功能相比,Math 对象提供的计算功能执行起来要快得多。

  注意:

    Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。

    您无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。

 

 

 

二、Math 对象的属性:

    Math 对象包含的属性大都是数学计算中可能会用到的一些特殊值。
技术分享

   alert(Math.E);                     
    alert(Math.LN10);                
    alert(Math.LN2);                
    alert(Math.LOG2E);
    alert(Math.LOG10E);
    alert(Math.PI);
    alert(Math.SQRT1_2);
    alert(Math.SQRT2);

 

 

 

 

三、Math 对象的方法:

  1.min()和 max()方法

    Math.min()用于确定一组数值中的最小值。

    Math.max()用于确定一组数值中的最大值。

    //max()方法
    document.write(Math.max(5,7) + "<br />");
    document.write(Math.max(-3,5) + "<br />");
    document.write(Math.max(-3,-5) + "<br />");
    document.write(Math.max(7.25,7.30));
    
    //min()方法
    document.write(Math.min(5,7) + "<br />");
    document.write(Math.min(-3,5) + "<br />");
    document.write(Math.min(-3,-5) + "<br />");
    document.write(Math.min(7.25,7.30));
    
    alert(Math.min(2,4,3,6,3,8,0,1,3)); //最小值
    alert(Math.max(4,7,8,3,1,9,6,0,3,2)); //最大值

 

 

  2.舍入方法
    Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;

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

    Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;

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

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

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

 

 

  3.random()方法:

    该方法返回介于 0 到 1 之间一个随机小数,不包括 0 和 1。

alert(Math.random());

    如果想获取大于这个范围的随机数的话,可以套用一下公式:值 = Math.floor(Math.random() * 总数 + 第一个值)

  //随机产生 1-10 之间的任意数

    //先获取随机小数
    var box  = Math.random();
    
    //将获取到的随机小数,乘以10等到0到10之间的小数,不包括0和10,最后加上1就可以等到1到10之间的小数
    box = box*10+1;
    
    //将后面的小数截取掉(即将数值向下舍入),变成整数
    box = Math.floor(box);

    alert(box);
    
    //写成一句话就是:alert(Math.floor(Math.random() * 10 + 1)); 
  for (var i = 0; i<10;i ++) {
        document.write(Math.floor(Math.random() * 10 + 5)); //5-14 之间的任意数 10+5-1=14
        document.write(‘<br />‘);
    }
    //如果想要5到10 10-5+1 = 6 就是*6+5

    为了更加方便的传递想要范围,可以定义一个函数:

  function selectFrom(lower, upper) {
        var sum = upper - lower + 1;                                 //总数-第一个数+1
        return Math.floor(Math.random() * sum + lower);
    }
    
    for (var i=0 ;i<10;i++) {
        document.write(selectFrom(5,100));                             //直接传递范围即可
        document.write(‘<br />‘);
    }

 

 

  4.其他方法

  技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。