ECMAScript 之如何判斷 undefined ?
undefined
是 ECMAScript 很特殊的存在,實務上有多種判斷方式。
Version
ECMAScript 5
Undefined
undefined
有兩種可能:
- 有宣告 variable,但還沒給定初始值
- 還未宣告 variable
=== undefined
foo
只有宣告,但沒有給定初始值,這種 undefined
可用 === undefined
抓到。
foo
連宣告都沒有,雖然也是 undefined
,但 === undefined
抓不到。
=== undefined
只能抓到有定義,但尚未初始化的 variable
typeof === ‘undefined’
foo
只有宣告,但沒有給定初始值,這種 undefined
可用 typeof
抓到,但回傳是 undefined
string,不是 undefined
value。
foo
連宣告都沒有,也是 undefined
,但 typeof
也可順利抓到 undefined
。
typeof
可以攔截到所有的 undefined
,無論是有宣告的 variable 但尚未初始化,或者根本沒有宣告的 variable
Falsy Value
undefined
是 Falsy Value,因此也可以使用 !
攔截到 undefined
。
false
、 0
、 ''
、 NaN
、 null
與 undefined
都是 Truthy Value,因此也可能同時攔截到非 undefined
foo
連宣告都沒有,也是 undefined
,但 Falsy Value 無法使用。
Object.prototype.toString()
foo
只有宣告,但沒有給定初始值,這種 undefined
也可用 Object.prototype.toString()
抓到,但要判斷的是 Undefined
string,第一個字母 U
要大寫。
foo
要借用 Object.prototype.toString()
,因此使用 call()
將 foo
傳進去,但 toString()
回傳為 [Object Undefined]
string,因此要再使用 slice()
加工取得 Undefined
foo
連宣告都沒有,也是 undefined
,但 Object.prototype.toString()
抓不到。
Conclusion
- 只有
typeof
可攔截到所有的undefined
,其判斷為undefined
string - Falsy Value 雖然方便,但可能會攔截到
undefined
以外的值,要小心使用 -
Object.prototype.toString()
會傳出比typeof
更詳細的型別資訊