【问题标题】:Uncaught ReferenceError (not defined) when checking === undefined检查 === 未定义时未捕获的 ReferenceError(未定义)
【发布时间】:2018-04-04 20:39:54
【问题描述】:

我有以下代码:

simpleExample.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple example</title>
</head>
<body>
    Open the Console.
    <script src="js/simpleExampleJS.js"></script>
</body>
</html>

js/simpleExampleJS.js:

MyObject = {
    COMPUTER_GREETING: "Hello World!",
    hello: function() {
        console.log(MyObject.COMPUTER_GREETING);
    }
};

checkSomeGlobal = function() {
    if(someGlobal === undefined) {
        console.log("someGlobal is undefined & handled without an error.");
    } else {
        console.log("someGlobal is defined.");
    }
};

MyObject.hello();
checkSomeGlobal();

当我运行它时,我得到:

Hello World!
Uncaught ReferenceError: someGlobal is not defined
at checkSomeGlobal (simpleExampleJS.js:9)
at simpleExampleJS.js:17

(第一行输出一般表示代码正在加载并运行)。

MDN indicates 表明一个可能未定义的变量可以用作严格相等/不相等 comparison 的左侧大小。然而在检查时if(someGlobal === undefined) 那行代码会产生一个错误,因为变量未定义,而不是使比较评估为true。如何检查和处理这个未定义的变量情况而不会出错?

【问题讨论】:

    标签: javascript comparison undefined comparison-operators


    【解决方案1】:

    那个错误是说没有这样的变量(它从未被声明过),而不是它的值是undefined

    要检查变量是否存在,可以写typeof someGlobal

    【讨论】:

    • 总结这个答案的解决方案,就是把第9行有问题的比较改成if(typeof someGlobal === "undefined")。谢谢你的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2011-01-05
    • 2016-01-02
    • 2013-10-06
    • 2016-12-17
    相关资源
    最近更新 更多