Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - 如何在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?

(我怎么能抓到这个错误?)

  ask by Jineesh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In JavaScript, null is an object.

(在JavaScript中, null是一个对象。)

There's another value for things that don't exist, undefined .

(对于不存在的事物,还有另一个值, 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.

(对于几乎无法在文档中找到某些结构的所有情况,DOM都返回null ,但在JavaScript本身中, undefined是使用的值。)

Second, no, there is not a direct equivalent.

(第二,不,没有直接的等价物。)

If you really want to check for specifically for null , 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)

Source

(资源)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...