首页 > 解决方案 > 您应该考虑开关中的 1 值吗?

问题描述

我正在申请一门编程课程,在被录取之前,我们还有 59 项任务要做。我在这里为转换练习而苦苦挣扎,我希望有人可以帮助我。

给我看代码

还记得骰子模拟器吗?继续将 if - else if - else 语句转换为 switch 语句,看看它是如何变得更容易阅读的。

var dieRoll = Math.ceil(Math.random() * 6); 
if (dieRoll === 1) {
    console.log('You roll a 1.');
} else if (dieRoll === 2) {
    console.log('You roll a 2.');
} else if (dieRoll === 3) {
    console.log('You roll a 3.');
} else if (dieRoll === 4) {
    console.log('You roll a 4.');
} else if (dieRoll === 5) {
    console.log('You roll a 5.');
} else if (dieRoll === 6) {
    console.log('You roll a 6.');
} else {
    console.log('This die only has 6 sides man...');
}

所以现在,我应该把它变成一个 switch 语句,这就是我要去的地方。

var dieRoll = Math.ceil(Math.random() * 6);
switch (dieRoll)    {
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
        console.log ('You roll a ' + dieRoll + '.');  
        break;
    default:
        console.log ('This die only has 6 sides man...');
}
console.log(dieRoll);

错误- 您应该考虑开关中的 1 值。

我做错了什么?

非常感谢。

标签: javascriptswitch-statement

解决方案


Aswitch的值case必须与正在切换的值完全相同。

var dieRoll = Math.ceil(Math.random() * 6);

dieRoll将是一个数字,从 1 到 6。它不会是一个字符串,所以

case <someString>

永远不会实现。

改用数字大小写:

var dieRoll = Math.ceil(Math.random() * 6);
switch (dieRoll) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
  case 6:
    console.log('You roll a ' + dieRoll + '.');
    break;
  default:
    console.log('This die only has 6 sides man...');
}

但是switch在这里用起来很奇怪,为什么不只是

console.log('You roll a ' + Math.ceil(Math.random() * 6) + '.')


推荐阅读