【发布时间】: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