【问题标题】:Reference Error from undefined check [duplicate]来自未定义检查的参考错误[重复]
【发布时间】: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


【解决方案1】:

问题是bar 不等于undefined。它根本没有定义。变量不存在。代码崩溃是因为你试图读取一个不存在的变量。

var bar;

// bar is not defined

if (bar) console.log("should not execute");

if (!bar) console.log("should execute");

var foo = bar || 'foo'; // foo is now 'foo'

【讨论】:

  • 严格模式在这里无关紧要。它会阻止您声明一个隐式全局变量,但您永远无法读取未声明的变量。
  • 修复了答案。我总是在严格模式下工作,时间让我相信这个“​​功能”来自严格模式。
猜你喜欢
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2021-12-11
  • 1970-01-01
相关资源
最近更新 更多