How to check a not

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?


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.

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`

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)

Source


The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).


Technically, the proper solution is (I believe):

typeof x === "undefined"

You can sometimes get lazy and use

x == null

but that allows both an undefined variable x, and a variable x containing null, to return true.

链接地址: http://www.djcxy.com/p/12860.html

上一篇: 检查一个字符串是否与JS中的正则表达式匹配

下一篇: 如何检查一个不是