我想弄清楚为什么这段代码不起作用
let userName = 'roy';
const userQuestion = 'Do you do CrossFit?';
userName ? console.log('Hello ' + userName + ' !') : console.log('Hello!');
console.log(`The user asked: ${userQuestion}`);
let randomNumber = Math.floor(Math.random() * 8);
let eightBall = '';
console.log(randomNumber);
switch (randomNumber) {
case 0:
eightBall = 'It is certain';
break;
case 1:
eightBall = 'It is defidedly so';
break;
case randomNumber >= 1:
eightBall = 'we cant tell';
break;
}
console.log(` The eight ball answered: ${eightBall}`);
当数字大于1时,尝试生成“我们可以告诉”,但它不会打印任何内容。我使用switch语句错了吗?
答案 0 :(得分:2)
使用带有if
语句的默认值,如下所示:
let randomNumber = 100
let eightBall = ''
switch (randomNumber) {
case 0:
eightBall = 'It is certain';
break;
case 1:
eightBall = 'It is defidedly so';
break;
default:
if(randomNumber >= 1)
eightBall = 'we cant tell';
break;
}
console.log(` The eight ball answered: ${eightBall}`);
答案 1 :(得分:2)
case
也使参数相等,而不是布尔表达式。您可以使用default
分支:
switch (randomNumber) {
case 0:
eightBall = 'It is certain';
break;
case 1:
eightBall = 'It is defidedly so';
break;
default: // Here!
eightBall = 'we cant tell';
break;
}