大于和小于switch语句

时间:2018-04-17 15:11:23

标签: javascript

我想弄清楚为什么这段代码不起作用

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语句错了吗?

2 个答案:

答案 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;
}