Javascript 测试一个变量是否在javascript中定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7578917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:48:26  来源:igfitidea点击:

Test if a variable is defined in javascript?

javascript

提问by boom

How should I test if a variable is defined?

我应该如何测试变量是否已定义?

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

回答by mithunsatheesh

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

find more explanation here:

在这里找到更多解释:

JavaScript isset() equivalent

JavaScript isset() 等效

回答by Anurag

Use the inoperator.

使用in运算符。

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

typeofchecks will return true for a variable if,

typeof如果,检查将为变量返回 true,

  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.
  1. 它没有被定义
  2. 它已被定义并具有值undefined,或
  3. 它已被定义但尚未初始化。

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

回答by Brian Antonelli

You simply check the type.

您只需检查类型。

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

回答by xyz

You can use something like this

你可以使用这样的东西

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

    }