在 Javascript 中检查未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6407104/
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-23 21:35:11  来源:igfitidea点击:

Checking for Undefined in Javascript

javascriptundefined

提问by Krishnan

I was following the below logic to check if a variable is undefined or not:

我遵循以下逻辑来检查变量是否未定义:

 if (variable==undefined){
////implementation
}

But found that for some cases it did not function as expected. So, tried this approach,

但是发现在某些情况下它没有按预期运行。所以,尝试了这种方法,

if(typeof(variable) == "undefined"){
/////implementation
}

So which one is most reliable?

那么哪个最靠谱呢?

采纳答案by Asaph

Your second way is the most reliable but you don't need the parenthesis for the typeofoperator. See this question.

您的第二种方法是最可靠的,但您不需要typeof运算符的括号。看到这个问题

回答by amit kate

if (variableName){
////implementation
}

this way is more use full than second option

这种方式比第二种选择更充分利用