我正在申请编程类(class),在被录取之前我们还有 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 值。
我做错了什么?
非常感谢。
最佳答案
switch
的 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) + '.')
关于javascript - 您应该考虑开关中的 1 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362150/