引用对象-Math对象

2017-04-02  本文已影响0人  章丸丸
1.min()max()方法
var min = Math.min(3,54,74,9);
var max = Math.max(3,54,74,9);
console.log(min);         //3
console.log(max);         //74
2.舍入方法(小数值舍入为整数的方法)
console.log( Math.ceil(25.6) );      //26
console.log( Math.ceil(25.3) );      //26
console.log( Math.ceil(25.9) );      //26
console.log( Math.floor(25.6) );      //25
console.log( Math.floor(25.3) );      //25
console.log( Math.floor(25.9) );      //25
console.log( Math.round(25.6) );      //26
console.log( Math.round(25.3) );      //25
console.log( Math.round(25.9) );      //26
3.random()方法
var num = Math.floor( Math.random() * 10 + 1   );
console.log(num);           //可以取得1-10之间的整数(包括1和10)
4.写一个函数limit2,保留数字小数点后两位,四舍五入
function limit2(num){
    return Math.round( num * 100 ) / 100;
}
console.log( limit2(3.456) );   //3.46
console.log( limit2(2.42) );    //2.42
5.写一个函数,获取从minmax之间的随机数,包括min不包括max
function getNum(min,max){
        return Math.random()*(max-min)+min;
}
console.log( getNum(1,10) );
6.写一个函数,获取从min都max之间的随机整数,包括min包括max
   function getNum(min,max){
        return Math.floor(Math.random()*(max-min+1)+min);
   }
   console.log( getNum(1,3) );
7.写一个函数,获取一个随机数组,数组中元素为长度为len,最小值为min,最大值为max(包括)的随机数
    function randomNum(len,min,max){
          var arr = [];
          for(i=0;i<len;i++){
              arr.push( Math.floor( Math.random()*(max-min+1)+min) );
          }
          return arr;
    }
    console.log(randomNum(3,1,4));
上一篇 下一篇

猜你喜欢

热点阅读