JavaScript switch语句不起作用-三个太多了吗?

时间:2018-07-17 01:58:24

标签: javascript

我是Java语言的新手,我正在尝试通过编写一些程序来学习,您可以在其中输入占星术的符号,行星和房屋,以制作一些疯子般的故事。为此,我将三个switch语句放在一个函数中。

不确定那是否有太多switch语句,但是,当我在Chrome上加载它时,有时我只会收到文本,有时会收到text和text2,有时只会收到text3。

有人知道为什么会这样吗?我在一个函数中是否简单地拥有太多switch语句?我在线搜索,但找不到一个函数中允许有多少个。

function tellMeaStory() {
  var text;
  var text2;
  var text3;
  var sign = document.getElementById("mySign").value;
  var planet = document.getElementById("myPlanet").value;
  var house = document.getElementById("myHouse").value;

  switch(sign) {
    case "Aries", "aries":
      text = "red";
      break;
    case "Taurus", "taurus":
      text = "calm";
      break;
    case "Gemini", "gemini":
      text = "quirky";
      break;
    case "Cancer", "cancer":
      text = "moody";
      break;
    case "Leo", "leo":
      text = "hungry";
      break;
    default:
      text = "sign";
  }

  switch(planet) {
    case "Sun", "sun":
      text2 = "hero";
      break;
    case "Moon", "moon":
      text2 = "mother";
      break;
    case "Mercury", "mercury":
      text2 = "twin";
      break;
    case "Venus", "venus":
      text2 = "courtesan";
      break;
    case "Mars", "mars":
      text2 = "soldier";
      break;
    default:
      text2 = "planet";
  }

  switch(house) {
    case "one", "One":
      text3 = "hole";
      break;
    case "two", "Two":
      text3 = "buffet";
      break;
    case "three", "Three":
      text3 = "database";
      break;
    case "four", "Four":
      text3 = "stomach";
      break;
    case "five", "Five":
      text3 = "wilderness";
      break;
    default:
      text3 = "house";
  }
  document.getElementById("demo").innerHTML += "You are a " + text + " " + text2 + " in a " + text3;
}
<input id="mySign" type="text" value="Enter your sign">
<input id="myPlanet" type="text" value="Enter your planet">
<input id="myHouse" type="text" value="Enter your house">

<button onclick="tellMeaStory()">Generate</button>
<div id="demo"></div>

1 个答案:

答案 0 :(得分:1)

您看到奇怪结果的原因是因为JavaScript如何处理逗号。例如,case "Sun", "sun":不检查大小写是sun还是Sun,而是创建一个字符串"sun""Sun"进行比较。 switch语句没有限制,但是对于“大多数”情况而言,它们并不是很好。如果要重写此代码以检查多种拼写,可以执行以下两种方法之一,至少我能想到。

撤销您的switch语句

  switch(true) {
case (planet.toUpperCase() === "SUN"):
  text2 = "hero";
  break;
case (planet.toUpperCase() === "MOON"):
  text2 = "mother";
  break;
case (planet.toUpperCase() === "MERCURY"):
  text2 = "twin";
  break;
case (planet.toUpperCase() === "Venus"):
  text2 = "courtesan";
  break;
case (planet.toUpperCase() === "MARS"):
  text2 = "soldier";
  break;
default:
  text2 = "planet";
}

或者您可以使用一系列if语句,一起跳过所有开关。

if(planet === "sun" || planet === "Sun" || planet === "SUn") {
  // text assignment
}

if (planet.toLowerCase() === "sun") { 
  // text assignment 
}

您可以了解有关逗号运算符here的更多信息。