JS中Math函數(shù)的常用方法
Math 是數(shù)學(xué)函數(shù)窝剖,但又屬于對(duì)象數(shù)據(jù)類(lèi)型 typeof Math => ‘object’
console.dir(Math) 查看Math的所有函數(shù)方法。
1诚隙,Math.abs() 獲取絕對(duì)值
Math.abs(-12) = 12
2,Math.ceil() and Math.floor() 向上取整和向下取整
console.log(Math.ceil(12.03));//13
console.log(Math.ceil(12.92));//13
console.log(Math.floor(12.3));//12
console.log(Math.floor(12.9));//12
3,Math.round() 四舍五入
注意:正數(shù)時(shí),包含5是向上取整半夷,負(fù)數(shù)時(shí)包含5是向下取整。
1列荔、Math.round(-16.3) = -16
2砂吞、Math.round(-16.5) = -16
3蜻直、Math.round(-16.51) = -17
4,Math.random() 取[0,1)的隨機(jī)小數(shù)
案例1:獲取[0,10]的隨機(jī)整數(shù)
console.log(parseInt(Math.random()10));//未包含10
console.log(parseInt(Math.random()10+1));//包含10
案例2:獲取[n,m]之間的隨機(jī)整數(shù)
Math.round(Math.random()*(m-n)+n)
5,Math.max() and Max.min() 獲取一組數(shù)據(jù)中的最大值和最小值
console.log(Math.max(10,1,9,100,200,45,78));
console.log(Math.min(10,1,9,100,200,45,78));
6王悍,Math.PI 獲取圓周率π 的值
console.log(Math.PI);
7压储,Math.pow() and Math.sqrt()
Math.pow()獲取一個(gè)值的多少次冪
Math.sqrt()對(duì)數(shù)值開(kāi)方
1.Math.pow(10集惋,2) = 100;
2.Math.sqrt(100) = 10;
//例子:自己定義一個(gè)對(duì)象,實(shí)現(xiàn)系統(tǒng)的max的方法
function Mymax() {
//添加了一個(gè)方法
this.getMax = function () {
//假設(shè)這個(gè)數(shù)是最大值
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i];
}
}
return max;
};
}
// 實(shí)例對(duì)象
var my = new Mymax();
console.log(my.getMax(9, 5, 6, 32));
console.log(Math.max(9, 5, 6, 32));