NaN 代表 Not-a-Number,是一個特殊的數值,通常用來表示某個運算或轉換無法產生有效數字。NaN 與任何值比較都不相等,包括它自己。
若要判斷某個值是否為 NaN,可使用全域函式 isNaN()。若要更嚴格判斷是否為真正的 NaN 數值,可使用 Number.isNaN()。
function showValue() {
let dayOfMonth = 50;
if (dayOfMonth > 31) {
dayOfMonth = Number.NaN;
alert('Day of Month must be between 1 and 31.');
}
alert('Value of dayOfMonth : ' + dayOfMonth);
}
當日期超出合理範圍時,可將變數設為 NaN,提醒後續邏輯此值無效。