javascript 检查 === 未定义时未捕获的 ReferenceError(未定义)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49660037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught ReferenceError (not defined) when checking === undefined
提问by WBT
I have the following code:
我有以下代码:
simpleExample.html:
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:
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();
When I run this, I get:
当我运行这个时,我得到:
Hello World!
Uncaught ReferenceError: someGlobal is not defined
at checkSomeGlobal (simpleExampleJS.js:9)
at simpleExampleJS.js:17
(The first line of output generally indicates that the code is loading and running).
(第一行输出一般表示代码正在加载和运行)。
MDN indicatesthat a potentially undefined variable can be used as the left-hand-size of a strict equal/non-equal comparison. Yet when checkingif(someGlobal === undefined)that line of code produces an errorbecause the variable is undefined, instead of making the comparison evaluate to true. How can I check for and handle this undefined variable case without an error?
MDN表明一个潜在的未定义变量可以用作严格相等/不等比较的左侧大小。然而,在检查if(someGlobal === undefined)该行代码时会产生错误,因为变量未定义,而不是使比较评估为true。如何检查和处理这个未定义的变量情况而不会出错?
回答by SLaks
That error is saying that there is no such variable (it was never declared), not that its value is undefined.
该错误是说没有这样的变量(它从未被声明过),而不是它的值是undefined.
To check whether a variable exists, you can write typeof someGlobal
要检查变量是否存在,您可以编写 typeof someGlobal

