ES6 -- 新內建方法取代舊內建方法: 判斷數字
當我們想判斷是不是NaN或Finite的數字時:
在ES5中會這麼寫:
e.g.
var isNaN = function(n) {
return n !== n; // 因NaN !== NaN, 所以用這個來當判斷點
};
var isFinite = function(v) {
return (typeof v === "number" && !isNaN(v) && v !== Infinity && v !== -Infinity);
};
console.log(isNaN(42) === false);
console.log(isNaN(NaN) === true);
console.log(isFinite(Infinity) === false);
console.log(isFinite(-Infinity) === false);
console.log(isFinite(NaN) === false);
console.log(isFinite(123) === true);
p.s. 以上輸出結果全是"true"
在ES6中會使用Number.isNaN()和Number.isFinite():
e.g.
console.log(Number.isNaN(42) === false);
console.log(Number.isNaN(NaN) === true);
console.log(Number.isFinite(Infinity) === false);
console.log(Number.isFinite(-Infinity) === false);
console.log(Number.isFinite(NaN) === false);
console.log(Number.isFinite(123) === true);
p.s. 以上輸出結果全是"true"
在ES5中會這麼寫:
e.g.
var isNaN = function(n) {
return n !== n; // 因NaN !== NaN, 所以用這個來當判斷點
};
var isFinite = function(v) {
return (typeof v === "number" && !isNaN(v) && v !== Infinity && v !== -Infinity);
};
console.log(isNaN(42) === false);
console.log(isNaN(NaN) === true);
console.log(isFinite(Infinity) === false);
console.log(isFinite(-Infinity) === false);
console.log(isFinite(NaN) === false);
console.log(isFinite(123) === true);
p.s. 以上輸出結果全是"true"
在ES6中會使用Number.isNaN()和Number.isFinite():
e.g.
console.log(Number.isNaN(42) === false);
console.log(Number.isNaN(NaN) === true);
console.log(Number.isFinite(Infinity) === false);
console.log(Number.isFinite(-Infinity) === false);
console.log(Number.isFinite(NaN) === false);
console.log(Number.isFinite(123) === true);
p.s. 以上輸出結果全是"true"
留言
張貼留言