perhaps? 2010-08-02 17:53 采纳率: 100%
浏览 457
已采纳

如何在 JavaScript 中检查"未定义"? [复制]

What is the most appropriate way to test if a variable is undefined in JavaScript? I've seen several possible ways:

if (window.myVariable)

Or

if (typeof(myVariable) != "undefined")

Or

if (myVariable) //This throws an error if undefined. Should this be in Try/Catch?
</div>

转载于:https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript

  • 写回答

16条回答 默认 最新

  • 喵-见缝插针 2010-08-02 17:58
    关注

    If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example.

    // global scope
    var theFu; // theFu has been declared, but its value is undefined
    typeof theFu; // "undefined"
    

    But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

    "theFu" in window; // true
    "theFoo" in window; // false
    

    If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator.

    if (typeof myVar != 'undefined')
    

    The typeof operator is guaranteed to return a string. Direct comparisons against undefined are troublesome as undefined can be overwritten.

    window.undefined = "omg";
    "omg" == undefined // true
    

    As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

    if (window.myVar) will also include these falsy values, so it's not very robust:

    false
    0
    ""
    NaN
    null
    undefined
    

    Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.

    // abc was never declared.
    if (abc) {
        // ReferenceError: abc is not defined
    } 
    

    The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

    // or it's a property that can throw an error
    Object.defineProperty(window, "myVariable", { 
        get: function() { throw new Error("W00t?"); }, 
        set: undefined 
    });
    if (myVariable) {
        // Error: W00t?
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)