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?
提问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:
在这里找到更多解释:
回答by Anurag
Use the in
operator.
使用in
运算符。
'myVar' in window; // for global variables only
typeof
checks will return true for a variable if,
typeof
如果,检查将为变量返回 true,
- it hasn't been defined
- it has been defined and has the value
undefined
, or - it has been defined but not initialized yet.
- 它没有被定义
- 它已被定义并具有值
undefined
,或 - 它已被定义但尚未初始化。
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
}