JavaScript的數值參數「Number」:
將參數轉換成為數值狀態,如碰到非數值則回傳’NaN’。
function callNum(x) {
return Number(x)
}
console.log(callNum('1'));
// expected output: 1
console.log(callNum('NotANumber'));
// expected output: NaN
JavaScript的數值方法:
Number.isNaN(): 判斷傳入的值,是不是NaN。
Number.isFinite(): 判斷傳入的值,是不是一個有限的數值。
Number.inInteger(): 判斷傳入的直,是不是一個整數。
Number.isSafeInteger(): 判斷傳入的值,是不是在JavaScript中IEEE-754範圍間(-(2^53 -1) <= x <= (2^53 - 1)。
Number.parseFloat(): 判斷傳入的值如有「+、-、0-9、.、或科學符號」,返回當前解析到的浮點數。
ex.如下:
function circumference(r) {
return Number.parseFloat(r) * 2.0 * Math.PI;
}
console.log(circumference(4.567));
// expected output: 28.695307297889173
console.log(circumference('4.567abcdefgh'));
// expected output: 28.695307297889173
console.log(circumference('abcdefgh'));
// expected output: NaN
Number.parseInt(): 將傳入的字串轉換成數值,並且確認「+、-」的整數狀態,並且移除空白與字串。
ex.如下:
function roughScale(x, base) {
const parsed = parseInt(x, base);
if (isNaN(parsed)) { return 0; }
return parsed * 100;
}
console.log(roughScale("015", 10));
// expected output: 1500
console.log(roughScale('321', 2));
// expected output: 0
JavaScript的數值屬性:
Number.EPSILON: 介於1和大於1的最小值。 Number.MAX_SAFE_INTEGER: 在JavaScript中IEEE-754範圍間的最大正整數(2^53 - 1)。 Number.MAX_VALUE: 可表示的最大正整數。 Number.MIN_SAFE_INTEGER: 在JavaScript中IEEE-754範圍間的最小正整數(-(2^53 - 1))。 Number.MIN_VALUE: 可表示的最小值。 Number.NaN: 特別用來表示非數值的物件。 Number.POSITIVE_INFINITY: 特別用來表示正無窮的數值。 Number.NEGATIVE_INFINITY: 特別用來表示負無窮的數值。 Number.prototype: 允許被添加到 Number 物件的屬性。