Math基礎(chǔ)
專門用于封裝數(shù)學(xué)計(jì)算所用的API或常量
Math不能new
Math的API
1.取整
1>上取整:Math.ceil(num); 只要小數(shù)點(diǎn)超過(guò),就取下一個(gè)整數(shù)。(ceil天花板)
var num = 123.001;
Math.ceil(num); // 124
var num = 123.000;
Math.ceil(num); ? //123
2>下取整:Math.floor(num); ?舍棄小數(shù)部分 ?(floor 地板)
var num = 123.999
Math.floor(num); //123
Math.floor(num) ?vs ? parseInt(str);
1.兩者都是舍棄小數(shù)部分慎王,取整
2.Math.floor(num)只能 對(duì)純數(shù)字下取整壹蔓;parseInt(str)去掉末位的非數(shù)字下取整
var n = "123.321a";
parseInt(n);//123
Math.floor(n); //NaN
3>四舍五入取整:Math.round(num)
var num = 123.321;
Math.round(num); // 123
Math.round(num);? ? vs? ? n.toFixed(d)
1.Math.round(num)只能取整,不能設(shè)定小數(shù)位數(shù)
? ?n.toFixed(d)可以按任意小數(shù)位數(shù)四舍五入
2.Math.round()返回值是數(shù)字僻他,可以直接參與數(shù)字運(yùn)算
? ?n.toFixed(d)返回的是字符串兽狭,參與運(yùn)算需要類型轉(zhuǎn)換。
var n = 123.321;
Math.round(n); // 123
n.toFixed(2); // 123.32
typeof ?n.toFixed(2) // string
type of n:查看n的數(shù)據(jù)類型
2.乘方和開平方
Math.pow(底數(shù)岔留,冪);
2的三次方 ? ?Math.pow(2,3); ? //8
Math.sqrt(num); 開平方
Math.sqrt(4) //2
3.最大值和最小值
1.Math.max(n);
Math.max(1,2,3,4); //4
2.Math.min(n);
Math.min(1,2,3,4); //1
max 和 min 不支持?jǐn)?shù)組類型的參數(shù)夏哭,解決方案:
Math.max.apply( undefined/math/null , arr ); ? // 獲取數(shù)組中的最大值
the first parameter , you pass to apply of any function,will be the this inside that function.but,max doesn't depend on the current context . so anything would in-place of math
4.隨機(jī)數(shù)
Math.random(); ? 0<=r<1
1.從min--max之間隨機(jī)生成一個(gè)隨機(jī)整數(shù)
parseInt ( Math.random()* (max - min + 1 ) + min);
2.從0-max之間生成一個(gè)隨機(jī)數(shù)
parseInt(Math.random()*(max+1))