1.数字类型检查
用于检查非数字和有限数字的新函数。
Number.isNaN()
Number.isFinite()
ECMAScript 6
Number.isNaN(42) === false
Number.isNaN(NaN) === true
Number.isFinite(Infinity) === false
Number.isFinite(-Infinity) === false
Number.isFinite(NaN) === false
Number.isFinite(123) === true
ECMAScript 5
var isNaN = function (n) {
return n !== n;
};
var isFinite = function (v) {
return (typeof v === "number" && !isNaN(v) && v !== Infinity && v !== -Infinity);
}
isNaN(42) === false;
isNaN(NaN) === true;
isFinite(Infinity) === false;
isFinite(-Infinity) === false;
isFinite(NaN) === false;
isFinite(123) === true;
2.数字安全检查
数字的安全范围:
大于等于-(2^53-1)=-9007199254740991,
小于等于2^53-1=9007199254740991
Number.isSafeInterger()
ECMAScript 6
Number.isSafeInterger(42) === true
Number.isSafeInterger(9007199254740992) === false
ECMAScript 5
function isSafeInteger (n) {
return (
typeof n === 'number'
&& Math.round(n) === n
&& -(Math.pow(2, 53) - 1) <= n
&& n <= (Math.pow(2, 53) - 1)
);
}
isSafeInterger(42) === true;
isSafeInterger(9007199254740992) === false
3.数字比较
标准Epsilon值的可用性,用于更精确地比较浮点数。
ECMAScript 6
console.log(0.1 + 0.2 === 0.3) // false
console.log(0.1 + 0.2) //0.30000000000000004
console.log(Number((0.1+0.2).toFixed(1)) === 0.3) //true
console.log(Math.abs((0.1 + 0.2)-0.3) < Number.EPSILON //true
ECMAScript 5
console.log(0.1 + 0.2 === 0.3); //false
console.log(Math.abs((0.1 + 0.2) - 0.3) < 2.220445049250313e-16);//true
4.数字截断
将浮点数截断为其整数部分,完全丢弃小数部分。
Math.trunc()
ECMAScript 6
console.log(Math.trunc(42.7)) //42
console.log(Math.trunc(0.1)) //0
console.log(Math.trunc(-0.1)) // -0
ECMAScript 5
function mathTrunc (x) {
return (x < 0 ? Math.ceil(x) : Math.floor(x));
}
console.log(mathTrunc(42.7)) //42
console.log(mathTrunc(0.1)) //0
console.log(mathTrunc(-0.1)) //-0
5.数字符号确定
确定数字的符号,包括有符号零和非数字的特殊情况。
Math.sign()
是正数则返回1;
负数返回-1;
0返回0;
-0返回-0;
ECMAScript 6
console.log(Math.sign(7)) //1
console.log(Math.sign(0)) //0
console.log(Math.sign(-0)) // -0
console.log(Math.sign(-7)) //-1
console.log(Math.sign(NaN)) //NaN
ECMAScript 5
function mathSign (x) {
return ((x === 0 || isNaN(x)) ? x : (x>0 ? 1: -1));
}
console.log(mathSign(7)) //1
console.log(mathSign(0)) //0
console.log(mathSign(-0)) // -0
console.log(mathSign(-7)) //-1
console.log(mathSign(NaN)) //NaN