【发布时间】:2018-03-01 11:39:53
【问题描述】:
未定义检查的结果令人困惑。
在我的记忆中并根据多个答案(12345),以下代码应该可以工作。
// bar is not defined
if (bar) console.log("should not execute");
if (!bar) console.log("should execute");
var foo = bar || 'foo'; // should assign 'foo' but is undefined
但在 Chrome(版本 63.0.3239)和 Firefox Nightly(版本 60.0a1)上,我得到了一个Uncaught ReferenceError: bar is not defined
这发生在没有严格模式的控制台和链接脚本上
// linked-script.js
(function() {
if (bar) console.log("should not execute");
if (!bar) console.log("should execute");
var foo = bar || 'foo';
})();
// index.html
<script type="text/javascript" src="linked-script.js"></script>
我错过了什么?
【问题讨论】:
-
请注意,
undefined不 等于false。例如console.log(undefined === false)返回false -
undefined != false很清楚,但链接的答案表明它应该检查未定义的变量
标签: javascript