如何从switch语句中获取变量的值是javascript

时间:2018-02-14 13:05:01

标签: javascript

var day = "Sunday";
var x;

switch (day) {
  case 0:
    var x = 5;
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
}

document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>

我想获得输出,因为今天是星期天5

但我得到的输出是今天星期日未定义

如何将值取为5而不是undefined ???

3 个答案:

答案 0 :(得分:1)

这是因为你在使用数字代替日期

的switch语句中的错误

喜欢案例0:而不是案例&#34;星期日&#34;  这是错误

&#13;
&#13;
var day = "Sunday";
var x;

switch (day) {
  case "Sunday":
    var x = 5;
    day = "Sunday";
    break;
  case "Monday":
    day = "Monday";
    break;
}

document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;

您也可以尝试这样与数字

  

getDay()方法将工作日作为0到6之间的数字返回。

     

(星期日= 0,星期一= 1,星期二= 2 ..)

此示例使用工作日编号计算工作日名称:

&#13;
&#13;
<p id="demo"></p>

<script>
var day;
var x=0;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
   
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case  6:
        day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day + x;
</script>
&#13;
&#13;
&#13;

  

如何将值取为5而不是undefined ???

javascript中的

变量将被初始化为undefined .so out out undefined,因为它在switch case中没有设置为5(条件无法协助)

答案 1 :(得分:0)

答案非常简单:

switch (day) {
 case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}

在上面的代码switch(day)中,你传递一个字符串“Sunday”和,如果它匹配一个int类型,如case 0,这是不可能的,所以尝试在switch()中传递一个int或像case "Sunday"这样的用例:

 switch (day) {
 case "Sunday":
var x = 5;
day = "Sunday";
break;
case "anyday"://use case as you want
day = "anyday";
break;
}

答案 2 :(得分:0)

您可能会发现使用对象来保存一组键/值更容易。然后,您可以使用day中保存的值检查对象。

&#13;
&#13;
const days = {
  sunday: 5,
  monday: 2
};

let day = "Sunday";

const demo = document.getElementById('demo');
demo.innerHTML = "Today is " + day + " " + days[day.toLowerCase()];
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;