我可以在 JavaScript 的 switch 语句中处理“未定义”的情况吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12696041/
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
Can I handle an "undefined" case in a switch statement in JavaScript?
提问by egucciar
If I'm passing an object to a case statement, and there is a case where it is undefined, can I handle that case? If so then how? If its not possible, then what is the best practice for handling an undefined case for a switch?
如果我将一个对象传递给 case 语句,并且存在未定义的情况,我可以处理这种情况吗?如果是,那么如何?如果不可能,那么处理开关未定义情况的最佳实践是什么?
回答by Jason McCreary
Add a case
for undefined
.
添加一个case
for undefined
。
case undefined:
// code
break;
Or, if all other options are exhausted, use the default
.
或者,如果所有其他选项都用尽,请使用default
.
default:
// code
break;
Note:To avoid errors, the variable supplied to switch
has to be declaredbut can have an undefined
value. Reference this fiddleand read more about defined and undefined variables in JavaScript.
注意:为避免错误,switch
必须声明提供给的变量,但可以有一个undefined
值。参考此小提琴并阅读有关JavaScript 中已定义和未定义变量的更多信息。
回答by ircmaxell
Well, the most portable way would be to define a new variable undefined
in your closure, that way you can completely avoid the case when someone does undefined = 1;
somewhere in the code base (as a global var), which would completely bork most of the implementations here.
好吧,最可移植的方法是undefined
在你的闭包中定义一个新变量,这样你就可以完全避免有人undefined = 1;
在代码库中的某个地方(作为全局变量)做的情况,这会使这里的大多数实现完全无聊。
(function() {
var foo;
var undefined;
switch (foo) {
case 1:
//something
break;
case 2:
//something
break;
case undefined:
// Something else!
break;
default:
// Default condition
}
})();
By explicitly declaring the variable, you prevent integration issues where you depend upon the global state of the undefined
variable...
通过显式声明变量,可以防止依赖于undefined
变量全局状态的集成问题......
回答by I Hate Lazy
If you're comparing object references, but the variable may not be assigned a value, it'll work like any other case to simply use undefined
.
如果您正在比较对象引用,但变量可能没有被赋值,那么它会像任何其他情况一样简单地使用undefined
.
var obs = [
{},
{}
];
var ob = obs[~~(Math.random() * (obs.length + 1))];
switch(ob) {
case obs[0]:
alert(0);
break;
case obs[1]:
alert(1);
break;
case undefined:
alert("Undefined");
break;
default: alert("some unknown value");
}
回答by jAndy
Since undefined
really is just another value('undefined' in window === true
), you can check for that.
由于undefined
真的只是另一个值( 'undefined' in window === true
),您可以检查它。
var foo;
switch( foo ) {
case 1:
console.log('1');
break;
case 2:
console.log('2');
break;
case 3:
console.log('3');
break;
case undefined:
console.log('undefined');
break;
}
works just about right.
工作得恰到好处。