简体   繁体   English

JavaScript运行时错误:检查是否未定义时,'variable'未定义

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

I have the following lines written with HTML and some inline JS: 我有以下用HTML和一些内联JS编写的行:

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

It produces this dynamic function code: 它产生这个动态函数代码:

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

As well as this error: 以及此错误:

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

Can anyone explain why this is happening? 任何人都可以解释为什么会这样吗?

It's because you're trying to access a variable that has never been defined. 这是因为您正在尝试访问从未定义过的变量。

Example: 例:

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

You can check if a variable has been declared using the typeof operator : 您可以使用typeof运算符检查是否已声明变量:

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

In order for Javascript to compare the value of the x variable it must look it up; 为了让Javascript比较x变量的值,它必须查找它; since it is not yet defined it throws an error message. 因为它尚未定义,所以会抛出错误消息。 This error is happening before the runtime even attempts to compare the value to undefined . 在运行时甚至尝试将值与undefined进行比较之前,会发生此错误。 It's a little bit of a chicken-and-egg problem. 这有点鸡蛋和鸡蛋的问题。

use typeof x === 'undefined' instead. 使用typeof x === 'undefined'代替。

Not totally sure what syntax <% [some javascript] %> is (Classic ASP?), but as an alternative, sniff if x exists on your global object. 不完全确定<% [some javascript] %>是什么语法(经典ASP?),但作为替代方案,如果x存在于您的全局对象上,则嗅探。

Since you've tagged this html , your global object should be window . 由于您已标记此html ,因此您的全局对象应该是window (In node, as an example, the global object is literally global .) (在节点中,作为示例,全局对象实际上是global 。)

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

And you're done. 而且你已经完成了。

You could also use the more verbose, but also more precise, code I think you intended in your post, so that if x is falsy but not null or undefined -- eg, 0 or "" -- it still trips the if . 您也可以使用我认为您在帖子中打算使用的更详细,但也更精确的代码,这样如果x是假的但不是nullundefined - 例如, 0"" - 它仍然会跳过if

Though I'm pretty sure you wanted an && in there, not an || 虽然我很确定你想要一个&& ,而不是|| . That is, as originally written, your condition will always evaluate true. 也就是说,按照最初的写法,您的条件将始终评估为真。 If x is undefined , then it's by definition not null , and vice versa! 如果x undefined ,那么它的定义不是null ,反之亦然!

Here's the tweaked version... 这是经过调整的版本......

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

variable x is not defined in your javascript code. 变量x未在您的javascript代码中定义。 Do a check with typeof operator. 使用typeof运算符进行检查。

typeof x=="undefined"

if if returns true then your variable x is not defined. 如果if返回true,则表示未定义变量x。

try this 试试这个

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

!x will return true for an empty string, NaN, null, undefined. !x将为空字符串返回true,NaN,null,undefined。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM