测试是否在javascript中定义了变量?

时间:2011-09-28 05:56:07

标签: javascript

如何测试变量是否定义?

if //variable is defined
    //do this
else
    //do this

4 个答案:

答案 0 :(得分:75)

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

在此处找到更多解释:

JavaScript isset() equivalent

答案 1 :(得分:8)

使用in运算符。

'myVar' in window; // for global variables only
对于变量if

typeof检查将返回true

  1. 尚未定义
  2. 已定义且值为undefined
  3. 已经定义但尚未初始化。
  4. 以下示例将说明第二点和第三点。

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

答案 2 :(得分:4)

您只需检查类型。

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

答案 3 :(得分:0)

你可以使用这样的东西

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

    }
相关问题