Math的最常用的十一种使用方法

1,211 阅读2分钟

Math

Math对象: 是js内置的一个操作数据的对象,就是做数学运算的一个对象;

1. random

语法 : 语法 : Math.random(); 随机生成 0-1之间的数字 包含0 不包含1

//0-1之间的随机数  包含0 不包含1
 var res=Math.random();
 console.log(res);//随机生成 0-1之间的数字
 
//1-10之间的随机数
var res=parseInt(Math.random()*10);
 console.log(res);
 
//10-20之间的随机数 
/var res = parseInt( Math.random()*10+10);
/console.log(res);

//30-40之间的随机数 
/var res = parseInt( Math.random()*10+30);
/console.log(res);

// 20-40之间的随机数 
var res = parseInt( Math.random()*20+20);
console.log(res);

// 0-40之间的随机数 
var res = parseInt(Math.random()*40);
console.log(res);

// min-max之间的随机数 ???(包前不包后)
var res = parseInt(Math.random()*(max-min)+min);
console.log(res);

// min-max之间的随机数 ???(包前也包后)就需要扩大一位数
var res = parseInt(Math.random()*(max+1-min)+min);
console.log(res);

//所以也可以封装一个函数,可以随机生成min-max之间的随机数 包含min 也包含max
function randNum(min,max){
    return parseInt(Math.random()*(max+1-min)+min);
}
randNum();

2.round : 四舍五入

var a = 1.5;
var res =  Math.round(a);
console.log(res);

比较随机0-10之间的数的两种方法的概率问题(包前也包后的两种方法)

//方法一:用+1  每个数出现的概率一样
function randNum(min,max){
    return parseInt(Math.random()*(max+1-min)+min);
}
console.log(randNum(0,10));//这种0-10之间每个数的概率相等
//方法二:用round  头尾出现的概率会比中间数小一点
function randNum(min,max){
    return Math.round((Math.random()*(max-min)+min));
}
// 0-0.5  ---> 0(概率小)
// 0.6-1.4999 ---> 1
// 1.5--2.4999--->2
// ....
// 9.5---9.9999---->10(概率小)
console.log(randNum(0,10));//0和10的概率小

3.ceil :向上取整 只能处理数字

var a = 1.43434;
var res =  Math.ceil(a);
console.log(res);//2    若1.1也会取值2

4.floor :向下取整 只能处理数字 属于math的数学方法

var a = 2.9;
var res = Math.floor(a);
console.log(res);

5.pow:取幂的方法

 var res= Math.pow(3,2); 
console.log(res);//9   就是执行3的平方

6.sqrt:平方根: 注意就是2次方的根

var res =  Math.sqrt(36);
console.log(res);//6

7.max: 取多个数中的最大值 ;

语法: 最大值 = Math.max(值1,值2,值3,值4);

8.min :取多个数中的最小值

语法: 最小值 = Math.min(值1,值2,值3);

9.abs: 取一个数的绝对值

语法: 绝对值 = Math.abs(值);

10.PI 圆周率

console.log( Math.PI); //系统预定义的

11.toFixed : 保留小数点后几位

var a = 3.1415926;
var res = a.toFixed(3);  //注意: toFixed 会把数字变成字符串
        // 注意: toFixed 会四舍五入 
console.log(res);//3.142