在所有代碼執(zhí)行前,作用域中就已經(jīng)存在兩個(gè)內(nèi)置對(duì)象:Global(全局)和Math。
在大多數(shù)ES實(shí)現(xiàn)中都不能直接訪問Global對(duì)象。不過,WEB瀏覽器實(shí)現(xiàn)了承擔(dān)該角色的window對(duì)象。
全局變量和函數(shù)都是Global對(duì)象的屬性。
Math對(duì)象提供了很多屬性和方法,用于輔助完成復(fù)雜的數(shù)學(xué)計(jì)算任務(wù)。
1 Math.random()方法 功能: 返回0-1之間的隨機(jī)數(shù)
例子:
for(var i=0;i<1;i++){
console.log(Math.random());
}
2 Math.ceil(x)方法 功能: 對(duì)數(shù)字x向上取整
注意: 如果x是正數(shù) 向上取 如果是負(fù)數(shù) 可以直接理解為不要小數(shù)的部分(也是向上取整)
例子:
// 如果是正數(shù)
console.log(Math.ceil(2.4)); // 3
console.log(Math.ceil(2.8)); // 3
// 如果是負(fù)數(shù)
console.log(Math.ceil(-1.4)); // -1
console.log(Math.ceil(-1.8)); // -1
3 Math.floor()方法 功能: 對(duì)數(shù)字x向下取整
例子:
console.log(Math.floor(2.4)); // 2
console.log(Math.floor(2.8)); // 2
// 如果是負(fù)數(shù)
console.log(Math.floor(-1.4)); // -2
console.log(Math.floor(-1.8)); // -2
4 Math.round()方法 功能: 對(duì)數(shù)字x四舍五入取整(注意最后還是一個(gè)整數(shù))
console.log(Math.round(2.4)); // 2
console.log(Math.round(2.8)); // 3
// 如果是負(fù)數(shù)
console.log(Math.round(-1.4)); // -1
console.log(Math.round(-1.8)); // -2
5.Math.abs(),絕對(duì)值,功能:返回任意數(shù)值的絕對(duì)值
例子:
console.log(Math.abs(-1));//1
console.log(Math.abs('1px'));//NaN
console.log(Math.abs(1,2,3));//1
6.Math.min() 和 Math.max() , 功能:這兩個(gè)方法用于確定一組數(shù)值中的最小值和最大值。
例子:
var min = Math.min(1,2,3,4,5); //1
var min = Math.max(1,2,3,4,5); //5
//可以隱式類型轉(zhuǎn)換
var min = Math.min(1,2,3,4,"5"); //1
var min = Math.max(1,2,3,4,"5"); //5
//如果參數(shù)有一個(gè)(或者隱式類型轉(zhuǎn)換后)是非數(shù)值型,則返回NaN
var min = Math.min(1,2,3,4,"5aa"); //NaN
var min = Math.max(1,2,3,4,"5bb"); //NaN
如果要想找到數(shù)組的最大最小值,用apply()方法
例子:
var arr = [1,2,3,4,5];
var min = Math.min.apply(Math,arr);//
其他方法
方法 說明
Math.abs(number) 返回number的絕對(duì)值
Math.exp(number) 返回Math.E的number次冪
Math.log(number) 返回number的自然對(duì)數(shù)
Math.pow(number,power) 返回number的power次冪
Math.sqrt(number) 返回number的平方根
Math.acos(x) 返回x的反余弦值
Math.asin(x) 返回x的反正弦值
Math.atan(x) 返回x的反正切值
Math.atan2(y,x) 返回y/x的反正切值
Math.cos(x) 返回x的余弦值
Math.sin(x) 返回x的正弦值
Math.tan(x) 返回x的正切值