isNaN
函式
與其他 JavaScript 的值不同,你不可能靠等號運算符(== 與 ===)來判斷某個值是不是
NaN
,因為連
NaN == NaN
與
NaN === NaN
的結果都是
false
。因此,
isNaN
函式是必要的。
NaN
值的來源
NaN
會在算術運算(arithmetic operations)出現
undefined
或是
unrepresentable
值的結果時產生。這些值不一定是溢出條件。
NaN
亦為試圖給毫無可用數字的原始值、予以強制運算之結果。
例如,零除以零的結果會是
NaN
——不過把其他數字除以零則不是
NaN
。
從最早的
isNaN
函式版本規範始,其針對非數值之行為,不斷教人困惑至極。當
isNaN
函式的參數並非
數字
型別時,此值會先強制轉換到數字。該值接著會測定此值是否為
NaN
。因此,當被強制轉換的非數字,給出了有效的非 NaN 值(經典案例為空的字串與布林原始值:它們在強制轉換時,會給予數字結果 0 或 1)時,會回傳不如預期的「false」值:以空的字串為例,它很明顯地「非數字」。這段教人糾結的點,乃出於「非數字」術語的「數字」一詞、由 IEEE-754 浮點值定義之事實而來。這個函式要解釋為「當這個值,被強制轉換為數值時,它還是 IEEE-754 的『非數字』值嗎?」的答案。
最新的 ECMAScript(ES2015)版本導入了
Number.isNaN()
函式。儘管
Number.isNaN
的
NaN
依舊維持了數字上的意義、而不是簡單的「非數字」,
Number.isNaN(x)
在偵測
x
為
NaN
與否時比較可靠。另外,如果在缺少
Number.isNaN
的情況下,通過表達式
(x != x)
來檢測變量
x
是否是 NaN 會更加的可靠。
一個
isNaN
的 polyfill 可以理解為(這個 polyfill 利用了
NaN
自身永不等於自身這一特性):
var isNaN = function (value) {
var n = Number(value);
return n !== n;
jsisNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// 字串
isNaN("37"); // false: "37" 轉換成數字的 37 後就不是 NaN 了
isNaN("37.37"); // false: "37.37" 轉換成數字的 37.37 後就不是 NaN 了
isNaN("123ABC"); // true: parseInt("123ABC") 是 123 但 Number("123ABC") 是 NaN
isNaN(""); // false: 空字串轉換成數字的 0 後就不是 NaN 了
isNaN(" "); // false: 有空白的字串轉換成數字的 0 後就不是 NaN 了
// 日期
isNaN(new Date()); // false
isNaN(new Date().toString()); // true
// 這個偵測的錯誤是不能完全信賴 isNaN 的理由
isNaN("blabla"); // true: "blabla" 被轉換為數字,將其解析為數字失敗後回傳了 NaN
實用的特殊狀況行為
當然,你能以更用途導向的方法去思考 isNaN():如果 isNaN() 回傳 false,那麼把 x 用在任何算術表達式都不會回傳 NaN。相反地,如果回傳 true,那麼把 x 用在任何算術表達式都會是 NaN。這在 JavaScript 的意義是 isNaN(x) == true 等於 x - 0 回傳 NaN(儘管在 JavaScript 裡面 x - 0 == NaN 永遠回傳 false,你因而無法測試)── 事實上,isNaN(x)、isNaN(x - 0)、isNaN(Number(x))、Number.isNaN(x - 0)、Number.isNaN(Number(x)) 在 JavaScript 裡面,都會回傳一樣的東西。而 isNaN(x) 是所有表達式裡面最短的一種。
比方說,你可以用這個式子,去測試函式的參數能不能透過算術處理(也就是能「像」數字一樣被利用)、否則就提供預設值之類的。你可以透過上下文的根據以隱式數值轉換(implicitly converting value),以使用 JavaScript 提供的全部功能。
jsfunction increment(x) {
if (isNaN(x)) x = 0;
return x + 1;
// 與 Number.isNaN() 一樣:
function increment(x) {
if (Number.isNaN(Number(x))) x = 0;
return x + 1;
// 以下範例的函式參數 x,isNaN(x) 都會回傳 false,
// 儘管 x 不是數字,依舊能用在算術表達式。
increment(""); // 1: "" 被轉換成 0
increment(new String()); // 1: 空字串的新字串物件被轉換成 0
increment([]); // 1: [] 被轉換成 0
increment(new Array()); // 1: 空陣列的新陣列物件被轉換成 0
increment("0"); // 1: "0" 被轉換成 0
increment("1"); // 2: "1" 被轉換成 1
increment("0.1"); // 1.1: "0.1" 被轉換成 0.1
increment("Infinity"); // Infinity: "Infinity" 被轉換成 Infinity
increment(null); // 1: null 被轉換成 0
increment(false); // 1: false 被轉換成 0
increment(true); // 2: true 被轉換成 1
increment(new Date()); // 回傳以毫秒為單位加 1,當今的日期/時間
// 以下範例的函式參數 x,isNaN(x) 都會回傳 false,而 x 的確是數字。
increment(-1); // 0
increment(-0.1); // 0.9
increment(0); // 1
increment(1); // 2
increment(2); // 3
// …等等…
increment(Infinity); // Infinity
// 以下範例的函式參數 x,isNaN(x) 都會回傳 true,x 也的確不是數字。
// 使得函式會被 0 取代,並回傳 1
increment(String); // 1
increment(Array); // 1
increment("blabla"); // 1
increment("-blabla"); // 1
increment(0 / 0); // 1
increment("0/0"); // 1
increment(Infinity / Infinity); // 1
increment(NaN); // 1
increment(undefined); // 1
increment(); // 1
// isNaN(x) 與 isNaN(Number(x)) 永遠一樣,不過這裡的 x 是強制存在的!
isNaN(x) == isNaN(Number(x)); // 針對所有 x 的值都是 true,x == undefined 也不例外,
// 因為 isNaN(undefined) == true 且 Number(undefined) 回傳 NaN,
// 不過……
isNaN() == isNaN(Number()); // false,因為 isNaN() == true 且 Number() == 0
Specification
- JavaScript
- Tutorials and guides
JavaScript Guide
- Introduction
- Grammar and types
- Control flow and error handling
- Loops and iteration
- Functions
- Expressions and operators
- Numbers and strings
- Representing dates & times
- Regular expressions
- Indexed collections
- Keyed collections
- Working with objects
- Using classes
- Using promises
- JavaScript typed arrays
- Iterators and generators
- Resource management
- Internationalization
- JavaScript modules
- References
Built-in objects
- AggregateError
- Array
- ArrayBuffer
- AsyncDisposableStack
- AsyncFunction
- AsyncGenerator
- AsyncGeneratorFunction
- AsyncIterator
- Atomics
- BigInt
- BigInt64Array
- BigUint64Array
- Boolean
- DataView
- Date
- decodeURI()
- decodeURIComponent()
- DisposableStack
- encodeURI()
- encodeURIComponent()
- Error
- escape()
- eval()
- EvalError
- FinalizationRegistry
- Float16Array
- Float32Array
- Float64Array
- Function
- Generator
- GeneratorFunction
- globalThis
- Infinity
- Int8Array
- Int16Array
- Int32Array
- InternalError
Non-standard
- Intl
- isFinite()
- isNaN()
- Iterator
- JSON
- Map
- Math
- NaN
- Number
- Object
- parseFloat()
- parseInt()
- Promise
- Proxy
- RangeError
- ReferenceError
- Reflect
- RegExp
- Set
- SharedArrayBuffer
- 字串
- SuppressedError
- Symbol
- SyntaxError
- Temporal
- TypedArray
- TypeError
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- undefined
- unescape()
- URIError
- WeakMap
- WeakRef
- WeakSet
Expressions & operators
- 加法(+)
- Addition assignment (+=)
- Assignment (=)
- async function expression
- async function* expression
- await
- Bitwise AND (&)
- Bitwise AND assignment (&=)
- Bitwise NOT (~)
- Bitwise OR (|)
- Bitwise OR assignment (|=)
- Bitwise XOR (^)
- Bitwise XOR assignment (^=)
- class expression
- Comma operator (,)
- 條件運算子
- 遞減運算子(--)
- 屬性的刪除
- 解構
- 相除運算子(/)
- Division assignment (/=)
- Equality (==)
- 指數運算子(**)
- Exponentiation assignment (**=)
- function expression
- function* expression
- Greater than (>)
- Greater than or equal (>=)
- Grouping operator ( )
- import.meta
- import()
- in
- 遞增運算子(++)
- Inequality (!=)
- instanceof
- Left shift (<<)
- Left shift assignment (<<=)
- Less than (<)
- Less than or equal (<=)
- Logical AND (&&)
- Logical AND assignment (&&=)
- Logical NOT (!)
- Logical OR (||)
- Logical OR assignment (||=)
- 相乘運算子(*)
- Multiplication assignment (*=)
- 建構子函數的使用
- new.target
- null
- Nullish coalescing assignment (??=)
- Nullish coalescing operator (??)
- Object initializer
- 運算子優先序
- 可選串連
- Property accessors
- Remainder (%)
- Remainder assignment (%=)
- Right shift (>>)
- Right shift assignment (>>=)
- Spread syntax (...)
- Strict equality (===)
- Strict inequality (!==)
- 相減運算子(-)
- Subtraction assignment (-=)
- super
- this
- typeof
- 一元負號運算子(-)
- 一元正號(+)
- Unsigned right shift (>>>)
- Unsigned right shift assignment (>>>=)
- void operator
- yield
- yield*
Regular expressions
- Backreference: \1, \2
- Capturing group: (...)
- Character class escape: \d, \D, \w, \W, \s, \S
- Character class: [...], [^...]
- Character escape: \n, \u{...}
- Disjunction: |
- Input boundary assertion: ^, $
- Literal character: a, b
- Lookahead assertion: (?=...), (?!...)
- Lookbehind assertion: (?<=...), (?<!...)
- Modifier: (?ims-ims:...)
- Named backreference: \k<name>
- Named capturing group: (?<name>...)
- Non-capturing group: (?:...)
- Quantifier: *, +, ?, {n}, {n,}, {n,m}
- Unicode character class escape: \p{...}, \P{...}
- Wildcard: .
- Word boundary assertion: \b, \B
Errors
- AggregateError: No Promise in Promise.any was resolved
- Error: Permission denied to access property "x"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: BigInt division by zero
- RangeError: BigInt negative exponent
- RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'
- RangeError: invalid array length
- RangeError: invalid date
- RangeError: precision is out of range
- RangeError: radix must be an integer
- RangeError: repeat count must be less than infinity
- RangeError: repeat count must be non-negative
- RangeError: x can't be converted to BigInt because it isn't an integer
- ReferenceError: "x" is not defined
- ReferenceError: assignment to undeclared variable "x"
- ReferenceError: can't access lexical declaration 'X' before initialization
- ReferenceError: must call super constructor before using 'this' in derived class constructor
- ReferenceError: super() called twice in derived class constructor
- SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
- SyntaxError: "0"-prefixed octal literals are deprecated
- SyntaxError: "use strict" not allowed in function with non-simple parameters
- SyntaxError: "x" is a reserved identifier
- SyntaxError: \ at end of pattern
- SyntaxError: a declaration in the head of a for-of loop can't have an initializer
- SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
- SyntaxError: arguments is not valid in fields
- SyntaxError: await is only valid in async functions, async generators and modules
- SyntaxError: await/yield expression can't be used in parameter
- SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
- SyntaxError: character class escape cannot be used in class range in regular expression
- SyntaxError: continue must be inside loop
- SyntaxError: duplicate capture group name in regular expression
- SyntaxError: duplicate formal argument x
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: functions cannot be labelled
- SyntaxError: getter and setter for private name #x should either be both static or non-static
- SyntaxError: getter functions must have no arguments
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: import declarations may only appear at top level of a module
- SyntaxError: incomplete quantifier in regular expression
- SyntaxError: invalid assignment left-hand side
- SyntaxError: invalid BigInt syntax
- SyntaxError: invalid capture group name in regular expression
- SyntaxError: invalid character in class in regular expression
- SyntaxError: invalid class set operation in regular expression
- SyntaxError: invalid decimal escape in regular expression
- SyntaxError: invalid identity escape in regular expression
- SyntaxError: invalid named capture reference in regular expression
- SyntaxError: invalid property name in regular expression
- SyntaxError: invalid range in character class
- SyntaxError: invalid regexp group
- SyntaxError: invalid regular expression flag "x"
- SyntaxError: invalid unicode escape in regular expression
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: label not found
- SyntaxError: missing : after property id
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing ] after element list
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: missing = in const declaration
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: negated character class with strings in regular expression
- SyntaxError: new keyword cannot be used with an optional chain
- SyntaxError: nothing to repeat
- SyntaxError: numbers out of order in {} quantifier.
- SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
- SyntaxError: parameter after rest parameter
- SyntaxError: private fields can't be deleted
- SyntaxError: property name __proto__ appears more than once in object literal
- SyntaxError: raw bracket is not allowed in regular expression with unicode flag
- SyntaxError: redeclaration of formal parameter "x"
- SyntaxError: reference to undeclared private field or method #x
- SyntaxError: rest parameter may not have a default
- SyntaxError: return not in function
- SyntaxError: setter functions must have one argument
- SyntaxError: string literal contains an unescaped line break
- SyntaxError: super() is only valid in derived class constructors
- SyntaxError: tagged template cannot be used with optional chain
- SyntaxError: Unexpected '#' used outside of class body
- SyntaxError: Unexpected token
- SyntaxError: unlabeled break must be inside loop or switch
- SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
- SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
- TypeError: 'x' is not iterable
- TypeError: "x" is (not) "y"
- TypeError: "x" is not a constructor
- TypeError: "x" is not a function
- TypeError: "x" is not a non-null object
- TypeError: "x" is read-only
- TypeError: already executing generator
- TypeError: BigInt value can't be serialized in JSON
- TypeError: calling a builtin X constructor without new is forbidden
- TypeError: can't access/set private field or method: object is not the right class
- TypeError: can't assign to property "x" on "y": not an object
- TypeError: can't convert BigInt to number
- TypeError: can't convert x to BigInt
- TypeError: can't define property "x": "obj" is not extensible
- TypeError: can't delete non-configurable array element
- TypeError: can't redefine non-configurable property "x"
- TypeError: can't set prototype of this object
- TypeError: can't set prototype: it would cause a prototype chain cycle
- TypeError: cannot use 'in' operator to search for 'x' in 'y'
- TypeError: class constructors must be invoked with 'new'
- TypeError: cyclic object value
- TypeError: derived class constructor returned invalid value x
- TypeError: getting private setter-only property
- TypeError: Initializing an object twice is an error with private fields/methods
- TypeError: invalid 'instanceof' operand 'x'
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid assignment to const "x"
- TypeError: Iterator/AsyncIterator constructor can't be used directly
- TypeError: matchAll/replaceAll must be called with a global RegExp
- TypeError: More arguments needed
- TypeError: null/undefined has no properties
- TypeError: property "x" is non-configurable and can't be deleted
- TypeError: Reduce of empty array with no initial value
- TypeError: setting getter-only property "x"
- TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
- TypeError: X.prototype.y called on incompatible type
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: unreachable code after return statement