几个月的Javascript切换语句

use*_*798 0 javascript

我有一个任务,用户在提示框中放入一个数字,月份出来.这是到目前为止的代码:

<script type="text/javascript">
var a = prompt("enter a month number please.");

var b = "";

    switch(a){
        case 1: b = "January";
            break;
        case 2: b = "February";
            break;
        case 3: b = "March";
            break;
        case 4: b = "April";
            break;
        case 5: b = "May";
            break;
        case 6: b = "June"; 
            break;
        case 7: b = "July";
            break;
        case 8: b = "August";
            break;
        case 9: b = "September";
            break;
        case 10: b = "October";
            break;
        case 11: b = "November";
            break;
        case 12: b = "December";
            break;
        }

if((a==12) || (a==1) || (a==2)){

    document.write(" It is " + a + ", which is in winter.")
}

if((a==3) || (a==4) || (a==5)){

    document.write(" It is " + a + ", which is in spring.")
}

if((a==6) || (a==7) || (a==8)){

    document.write(" It is " + a + ", which is in summer.")
}

if((a==9) || (a==10) || (a==11)){

    document.write(" It is " + a + ", which is in fall.")
}

</script>
Run Code Online (Sandbox Code Playgroud)

我的月份不是输出.相反,这个数字是我的输出.似乎我的switch语句被忽略,只做if语句.我迷失了我做错了什么.

Guf*_*ffa 8

您正在使用包含数字的变量而不是包含该字符串的变量.b在输出中使用:

document.write(" It is " + b + ", which is in winter.");
Run Code Online (Sandbox Code Playgroud)

您还可以将代码编写为:

var a = parseInt(prompt("enter a month number please."), 10);
var month = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var b = month[a - 1];
var season;
switch (a) {
  case 12:
  case 1:
  case 2: season = "winter"; break;
  case 3:
  case 4:
  case 5: season = "spring"; break;
  case 6:
  case 7:
  case 8: season = "summer"; break;
  case 9:
  case 10:
  case 11: season = "fall"; break;
}
document.write(" It is " + b + ", which is in " + season + ".");
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/Guffa/ZuXmP/