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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:13:38  来源:igfitidea点击:

Check for a switch case with null value in javascript

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 nullor "", 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 switchwill catch all the falsy values separately. These values include undefined, null, false, 0, and ''.

Aswitch将分别捕获所有虚假值。这些值包括undefinednullfalse0,和''

An ifstatement 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();
}