如何将大写字母转换为小写字母并存储在开关语句中的变量中

时间:2018-09-07 12:16:57

标签: javascript web

这是我的JavaScript代码,应该显示:Okay! Great choice We are working hard for your cake,如果我输入cak e或Cake(注意c用大写字母表示),但可以与cake一起使用,但是Cake不适用,pancake和大写字母p Pancake也一样:

var make=prompt("Hey! What you are up to cake or pancake?");
switch(make){
    case ("cake" || "Cake"):
    console.log("Okay! Great choice  We are working hard for your cake");
    break;
    case ("pancake" || "Pancake"):
        console.log("Okay! Great choice   We are working hard for your pancake");
    break;
    default:
    console.log("Sorry we Only have cake or pancake to choose from.");
}

3 个答案:

答案 0 :(得分:0)

如果||运算符的左侧为真值,则将其评估为左侧,否则,其评估将为右侧。

所以"cake" || "Cake"因为"cake"是一个真值,所以意味着"cake"

因此case ("cake" || "Cake"):的意思是case ("cake"):


如果您想在一个开关中有多个匹配项,请有多种情况。

case ("cake"):
case ("Cake"):
    // etc
    break;

答案 1 :(得分:0)

表达式"cake" || "Cake"的计算结果为true,因为这两个字符串都是 truthy 。因此,当将用户输入的值与该值进行比较时,例如"cake" == true,它的计算结果为true,因为用户的输入("cake")也是真实的。

要忽略用户输入的大小写,只需在比较之前将其转换为小写(通过make.toLowerCase())即可。

var make = prompt("Hey! What you are up to cake or pancake?");
switch (make.toLowerCase()) {
  case "cake":
    console.log("Okay! Great choice  We are working hard for your cake");
    break;
  case "pancake":
    console.log("Okay! Great choice   We are working hard for your pancake");
    break;
  default:
    console.log("Sorry we Only have cake or pancake to choose from.");
}

如果您不熟悉 truthy falsy 值的概念,则可以在此处阅读MDN的文档:https://developer.mozilla.org/en-US/docs/Glossary/Truthyhttps://developer.mozilla.org/en-US/docs/Glossary/falsy < / p>

答案 2 :(得分:0)

不变比较:

var make = prompt("Hey! What you are up to cake or pancake?");

if (make.localeCompare("cake".toUpperCase()) == -1) {
  console.log("Okay! Great choice  We are working hard for your cake");
} else if (make.localeCompare("pancake".toUpperCase()) == -1) {
  console.log("Okay! Great choice   We are working hard for your pancake");
} else {
  console.log("Sorry we Only have cake or pancake to choose from.");
}