回答

收藏

如何检查 JavaScript 中的“未定义”?

技术问答 技术问答 291 人阅读 | 0 人回复 | 2023-09-12

测试 JavaScript 最适合不定义变量的方法是什么?3 N0 P) {  l8 B4 L1 U; q
我见过几种可能的方法:
0 z" m; C) {7 Q" q! D* ]; V
    if (window.myVariable)
    ) n1 A# I  S3 C' ?* b; q& G$ d
或者
6 f7 u8 F4 p( w. r
    if (typeof(myVariable) != "undefined")1 x* ^4 C; K2 d. {: {0 W( x
或者
7 G4 ^/ n9 H5 o9 r
    if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
    ) U6 _( ?# U1 ?7 p4 m# j
               0 S+ h8 J# ]+ R# w, `& J
    解决方案:                                                               
" e3 p9 L# ]: Y+ i                                                                如果您有兴趣找出变量是否已被声明,无论其价值如何,请使用它in操作符是最安全的方法。考虑这个例子:
' ^# d+ ^( [. b6 `9 r* A
    // global scopevar theFu; // theFu has been declared,but its value is undefinedtypeof theFu; // "undefined"4 d4 ?# o) ]; F3 ]* T
但这可能不是某些情况下的预期结果,因为变量或属性已经声明但尚未初始化。in检查操作符更稳定。8 M2 A) [- m; ~& V" z
    "theFu" in window; // true"theFoo" in window; // false/ H$ d* |/ X) `, k# G3 ?
如果你想知道变量是否还没有声明,或者是否有 value undefined,请使用typeof它保证返回一个字符串:
7 o) r( c  P+ G* h' {' \
    if (typeof myVar !== 'undefined')3 D$ c3 x8 E1 V8 a2 D
直接比较undefined很麻烦,因为undefined可能被覆盖。
( j" w# D" {2 \1 B7 u9 v
    window.undefined = "foo";"foo" == undefined // true( X' L1 d& s* H* L0 v1 m0 r
正如@CMS 指出这已经在 ECMAScript 第 5 版修复,undefined不能写。- M, t9 ^5 f& O- v
if (window.myVar) 也会包括这些虚假值,所以不是很强:( I7 c% B2 i7 ^2 ^: g
false0""NaNnullundefined感谢@CMS 指出你的第三种情况 -if (myVariable)这两种情况也可能导致错误。首先,当变量尚未定义时,它会抛出一个ReferenceError.
' |3 v! \2 U7 O
    // abc was never declared.if (abc)      / ReferenceError: abc is not defined}
    2 ?* p; T  b/ b( F% |/ A& N- ]) o
另一种情况是变量已经定义,但是有一个 getter 函数,在调用时会引起错误。8 T, T7 g8 _9 c- \$ f3 [$ v2 _
    // or it's a property that can throw an errorObject.defineProperty(window,"myVariable",{     get: function() { throw new Error("W00t?"); ,    set: undefined });if (myVariable)      / Error: W00t?}
    , a# i9 [) i+ q9 V9 b0 b
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则