检查 === 未定义时未捕获的 ReferenceError(未定义)

WBT*_*WBT 4 javascript comparison undefined comparison-operators

我有以下代码:

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>
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

Hello World!
Uncaught ReferenceError: someGlobal is not defined
at checkSomeGlobal (simpleExampleJS.js:9)
at simpleExampleJS.js:17
Run Code Online (Sandbox Code Playgroud)

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

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

SLa*_*aks 7

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

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

  • 总结一下这个答案中的解决方案,就是将第 9 行有问题的比较更改为 `if(typeof someGlobal === "undefined")`。谢谢您的回答! (3认同)