开发者

Test if a variable is defined in javascript? [duplicate]

This question already exists: Closed 11 years ago.

How should I test if a variable is defined?

if //varia开发者_StackOverflow中文版ble is defined
    //do this
else
    //do this


if (typeof variable !== 'undefined') {
  // ..
}
else
{
     // ..
}

find more explanation here:

JavaScript isset() equivalent


Use the in operator.

'myVar' in window; // for global variables only

typeof checks will return true for a variable if,

  1. it hasn't been defined
  2. it has been defined and has the value undefined, or
  3. it has been defined but not initialized yet.

The following examples will illustrate the second and third point.

// defined, but not initialized
var myVar;
typeof myVar; // undefined

// defined, and initialized to undefined
var myVar = undefined;
typeof myVar; // undefined


You simply check the type.

if(typeof yourVar !== "undefined"){
  alert("defined");
}
else{
  alert("undefined");
}


You can use something like this

if (typeof varname !== 'undefined') {
    // do this
} else {   
    // do that
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜