问题描述
我想检查变量是否已定义。例如,以下内容抛出未定义的错误
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error
alert( x );
如何捕获此错误?
推荐答案
在JavaScript中, null
是一个对象。对于不存在的事物还有另一个值, undefined
。 DOM几乎在所有无法在文档中找到某些结构的情况下返回 null
,但在JavaScript本身中 undefined
是使用的值。
In JavaScript, null
is an object. There's another value for things that don't exist, undefined
. The DOM returns null
for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined
is the value used.
第二,不,没有直接的等价物。如果你真的想特意检查 null
,请执行:
Second, no, there is not a direct equivalent. If you really want to check for specifically for null
, do:
if (yourvar === null) // Does not execute if yourvar is `undefined`
如果你想检查一个变量是否存在,只能用尝试
/ catch
,因为 typeof
会将未声明的变量和使用 undefined
的值声明的变量视为等效。
If you want to check if a variable exists, that can only be done with try
/catch
, since typeof
will treat an undeclared variable and a variable declared with the value of undefined
as equivalent.
但是,要检查变量是否声明且不是未定义
:
But, to check if a variable is declared and is not undefined
:
if (typeof yourvar !== 'undefined') // Any scope
如果您知道该变量存在,并想检查其中是否存有任何值:
If you know the variable exists, and want to check whether there's any value stored in it:
if (yourvar !== undefined)
如果你想知道一个成员是否独立但不是关心它的价值是什么:
If you want to know if a member exists independent but don't care what its value is:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
如果你想知道变量是否是:
If you want to to know whether a variable is truthy:
if (yourvar)
这篇关于如何在JavaScript中检查未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!