javascript 在javascript中检查具有空值的开关盒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22471351/
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
Check for a switch case with null value in javascript
提问by user3363453
I have written the below code.
我写了下面的代码。
if(result === ""){
show("Something went wrong!!");
}
else if (result === "getID") {
show("success");
}
else {
doSomething();
}
How can I write this using a switch case statement in JavaScript. I'm not sure how can I check for a null value in a switch case condition.
如何使用 JavaScript 中的 switch case 语句编写此代码。我不确定如何在 switch case 条件下检查空值。
Could someone help me on this??
有人可以帮我吗?
回答by thefourtheye
In this example, it doesn't matter if result is null
or ""
, control will reach console.log("Something went wrong");
在这个例子中,无论结果是null
还是""
,控制都会达到console.log("Something went wrong");
switch (result) {
case null:
case "":
console.log("Something went wrong");
break;
case "getID":
console.log("Success");
break;
default:
console.log("doSomething");
}
回答by Steven Spungin
A switch
will catch all the falsy values separately. These values include undefined
, null
, false
, 0
, and ''
.
Aswitch
将分别捕获所有虚假值。这些值包括undefined
,null
,false
,0
,和''
。
An if
statement will report all as false.
一个if
语句将报告全部为假。
A snippet is worth 1000 words...
一个片段值 1000 字...
const input = [null, undefined, '', false, 0]
console.log('switch results')
input.forEach(result => {
switch (result) {
case false:
console.log("false");
break;
case "":
console.log("empty string");
break;
case null:
console.log("null");
break;
case undefined:
console.log("undefined");
break;
case 0:
console.log("0");
break;
default:
console.log("default");
}
})
console.log('if results')
input.forEach(result => {
if (!result) {
console.log(result + ' is false')
} else {
console.log(result + ' is true')
}
})
回答by user3004356
switch (result)
{
case "" :
document.write("Something went wrong!!<br>");
break;
case "getID":
document.write("success<br>");
break;
default: dosomething();
}