1、Math.trunc() 該方法用於取出一個小數的小數部分,返回整數部分。看例子吧: 2、Math.sign() 該方法用來判斷一個數到底是正數,負數,還是0。有五中返回值。看下麵例子吧: 參數為正數時,返回1; 參數為0時,返回0; 參數為-0時,返回-0; 參數為負數時,返回-1; 參數為其 ...
1、Math.trunc()
該方法用於取出一個小數的小數部分,返回整數部分。看例子吧:
Math.trunc(1.234); //1 Math.trunc(-2.34141); //-2 Math.trunc(3.9); //3 //對於非數值,Math.trunc會內部使用Number將其轉為數值 Math.trunc("12.87656"); //12 //對於空值和無法截取整數的值,返回NaN Math.trunc("a"); //NaN Math.trunc(); //NaN Math.trunc(NaN); //NaN
2、Math.sign()
該方法用來判斷一個數到底是正數,負數,還是0。有五中返回值。看下麵例子吧:
Math.sign(23.235); //1 Math.sign(25); //1 Math.sign(0); //0 Math.sign(0.0); //0 Math.sign(-0.0); //-0 Math.sign(-0); //-0 Math.sign(-2); //-1 Math.sign(-2.983958); //-1 Math.sign('a'); //NaN Math.sign(); //NaN Math.sign(NaN); //NaN
參數為正數時,返回1;
參數為0時,返回0;
參數為-0時,返回-0;
參數為負數時,返回-1;
參數為其他值時,返回NaN。
3、Math.cbrt()
該方法用於計算一個數的立方根,等同於Math.pow(n,1/3)方法。
Math.cbrt(8); //2 Math.cbrt(-64); //-4 //對於非數值,該方法內部也是先使用Number方法將其轉化為數值,再進行計算 Math.cbrt("125"); //5 Math.cbrt("a"); //NaN
4、Math.hypot()
該方法用於計算所有參數平方和的平方根。
Math.hypot(3,4); //5 Math.hypot(1,2,3); //3.741657386773941 Math.hypot(-5); //5 Math.hypot(); //0 Math.hypot(NaN); //NaN Math.hypot("a"); //NaN Math.hypot(3,'4'); //5 Math.hypot(3,'a'); //NaN
以上幾種方法均可以大大的簡化代碼,很方便。