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?
(我怎么能抓到这个错误?)
ask by Jineesh translate from soI 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?
(我怎么能抓到这个错误?)
ask by Jineesh translate from so In JavaScript, null
is an object.
(在JavaScript中, null
是一个对象。)
undefined
. (对于不存在的事物,还有另一个值, undefined
。)
null
for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined
is the value used. (对于几乎无法在文档中找到某些结构的所有情况,DOM都返回null
,但在JavaScript本身中, undefined
是使用的值。)
Second, no, there is not a direct equivalent.
(第二,不,没有直接的等价物。)
If you really want to check for specifically fornull
, do: (如果您确实想要专门检查null
,请执行以下操作:)
if (yourvar === null) // Does not execute if yourvar is `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.
(如果要检查变量是否存在,那只能通过try
/ catch
来完成,因为typeof
会将未声明的变量和使用undefined
值声明的变量视为等效变量。)
But, to check if a variable is declared and is not undefined
:
(但是,检查是否声明一个变量,而不是undefined
:)
if (typeof yourvar !== 'undefined') // Any scope
Beware, this is nonsense, because there could be a variable with name undefined
:
(请注意,这是无稽之谈,因为可能存在名称undefined
的变量:)
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)
(资源)