javascript - 您应该考虑开关中的 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 值。
我做错了什么?
非常感谢。
解决方案
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) + '.')
推荐阅读
- angular - 刷新具有 Angular 2 路由的现有 url 时 Nginx 404 错误
- javascript - IE 11 react 'promise' 未定义
- google-app-engine - Google AppEngine Flex 垃圾邮件活跃度和重复性检查
- php - 重新加载页面(发送表单)
- r - 从具有重复的双精度向量中选择 k 个最高值
- cobalt - 如何将钴内容文件移动到另一个路径
- tizen - 无法在 tizen 模拟器中的画布上加载视频
- apache-spark - 如何在 egestion 到 neteza 时解决此错误?错误输入行数达到 maxerrors 限制
- sql-server - 选择不同的查询
- excel - 工作表拆分后保持源格式