如何在 JavaScript 中检查未定义的变量 [英] How to check a not-defined variable in JavaScript
问题描述
我想检查变量是否已定义.例如下面抛出一个未定义的错误
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error
alert( x );
我怎样才能发现这个错误?
How can I catch this error?
推荐答案
在 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`
如果你想检查一个变量是否存在,那只能用 try
/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.
但是,检查一个变量是否被声明并且不是undefined
:
But, to check if a variable is declared and is not undefined
:
if (yourvar !== undefined) // Any scope
以前,必须使用 typeof
运算符来安全地检查 undefined,因为可以像变量一样重新分配 undefined
.旧的方式是这样的:
Previously, it was necessary to use the typeof
operator to check for undefined safely, because it was possible to reassign undefined
just like a variable. The old way looked like this:
if (typeof yourvar !== 'undefined') // Any scope
undefined
可重新赋值的问题已在 2009 年发布的 ECMAScript 5 中得到修复.您现在可以安全地使用 ===
和 !==
在不使用 typeof
的情况下测试 undefined
,因为 undefined
已经只读了一段时间.
The issue of undefined
being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use ===
and !==
to test for undefined
without using typeof
as undefined
has been read-only for some time.
如果你想知道一个成员是否独立存在但不关心它的值是什么:
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 中检查未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!