Math對象的擴(kuò)展
一. Math.trunc
Math.trunc方法用于去除一個數(shù)的小數(shù)部分,返回整數(shù)部分。
Math.trunc(4.1); // 4
Math.trunc(4.9); // 4
Math.trunc(-4.1); //-4
Math.trunc(-4.9); // -4
Math.trunc(-0.123); //-0
Tips: 對于非整數(shù),Math.trunc內(nèi)部使用Number方法將其先轉(zhuǎn)為數(shù)值。
Math.trunc('123.456');
//123
Tips: 對于空值和無法截取整數(shù)的值,返回NaN。
Math.trunc(NaN); //NaN
Math.trunc('foo'); //NaN
Math.trunc(); //NaN
二.Math.sign()
Math.sign方法用來判斷一個數(shù)到底是正數(shù)、負(fù)數(shù)、還是零。對于非數(shù)值,會先將其轉(zhuǎn)換為數(shù)值。
//參數(shù)為正數(shù),返回+1;
//參數(shù)為負(fù)數(shù),返回-1;
//參數(shù)為0,返回0;
//參數(shù)為-0,返回-0;
//其他值,返回NaN。
Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
Math.sign('9'); // +1
Math.sign('foo'); // NaN
Math.sign(); // NaN
三. Math.cbrt()
Math.cbrt方法用于計(jì)算一個數(shù)的立方根。
Math.cbrt(-1) // -1
Math.cbrt(0) // 0
Math.cbrt(1) // 1
Math.cbrt(2) // 1.2599210498948734
Tips:對于非數(shù)值,Math.cbrt方法內(nèi)部也是先使用Number方法將其轉(zhuǎn)為數(shù)值。
Math.cbrt('8'); //2
Math.cbrt('hello'); //NaN
四. Math.hupot()
Math.hypot方法返回所有參數(shù)的平方和的平方根。
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(3, 4, 'foo'); // NaN
Math.hypot(3, 4, '5'); // 7.0710678118654755
Math.hypot(-3); // 3
五.指數(shù)運(yùn)算符(**)
2 ** 2 // 4
2 ** 3 // 8
指數(shù)運(yùn)算符可以與等號結(jié)合,形成一個新的賦值運(yùn)算符(**=)。
let a =1.5;
a **= 2;
//等同于 a = a * a;
let b = 4;
b **= 3;
//等同于b = b*b*b