JavaScript runtime error: 'variable' is undefined while checking to see if undefined

JavaScript runtime error: 'variable' is undefined while checking to see if undefined

我用 HTML 和一些内联 JS 编写了以下行:

 <% if (x !== undefined || x !== null) { %>
  <div> Foo </div>
 <% } %>

它产生这个动态函数代码:

if (x !== undefined || x !== null) {...

还有这个错误:

0x800a1391 - JavaScript runtime error: 'x' is undefined

谁能解释为什么会这样?

这是因为您试图访问一个从未定义过的变量。

示例:

'use strict';
console.log(x);

您可以使用 typeof operator:

检查变量是否已声明

'use strict';
console.log(typeof x === 'undefined');

变量 x 未在您的 javascript 代码中定义。使用 typeof 运算符进行检查。

typeof x=="undefined"

if if returns true 那么你的变量 x 没有定义。

为了 Javascript 比较 x 变量的值,它必须查找它;由于尚未定义,因此会抛出一条错误消息。此错误发生在运行时甚至尝试将值与 undefined 进行比较之前。这是一个先有鸡还是先有蛋的问题。

改用typeof x === 'undefined'

试试这个

<% if (!x) { %>
  <div> Foo </div>
<% } %>

!x 将 return 为空字符串、NaN、null、未定义。

不完全确定 <% [some javascript] %> 是什么语法(经典 ASP?),但作为替代方案,嗅探全局对象上是否存在 x

既然你已经标记了这个 html,你的全局对象应该是 window。 (以node为例,全局对象字面上就是global。)

<% if (window.x) { %>
  <div> Foo </div>
<% } %>

大功告成。

您还可以使用更详细但也更精确的代码,我认为您打算在 post 中使用,这样如果 x 是假的 但不是 nullundefined -- 例如,0"" -- 它仍然触发 if.

虽然 我很确定你想要一个 &&,而不是 ||。也就是说,正如最初写的那样,您的条件将始终评估为真。如果 xundefined,那么根据定义它不是 null,反之亦然!

这是调整后的版本...

<% if (window.x !== undefined && window.x !== null) { %>
  <div> Foo </div>
<% } %>