为什么Switch语句只能使用true关键字? [英] Why Switch statement only working with true keyword?

查看:302
本文介绍了为什么Switch语句只能使用true关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么第一个不工作而第二个工作正常吗?

Can anyone explain to me why first one is not working and second one is working?

第一个陈述

function test(n) {
    switch (n) {
    case (n == 0 || n == 1):
        console.log("Number is either 0 or 1");
        break;
    case (n >= 2):
        console.log("Number is greater than 1")
        break;
    default:
        console.log("Default");
    }
}

第二声明

function test(n) {
    switch (true) {
    case (n == 0 || n == 1):
        console.log("Number is either 0 or 1");
        break;
    case (n >= 2):
        console.log("Number is greater than 1")
        break;
    default:
        console.log("Default");
    }
}


推荐答案

将使用 === 比较给予开关的参数。在你拥有的情况下,你有表达式导致 boolean 类型: n == 0 || n == 1 n> = 2 。当您传递一个数字时,它会尝试将您的数字与案例中表达式给出的结果进行比较。因此,例如,使用给定数字 1 ,它会尝试比较 1 ===(1 == 0 || 1 == 1) - > 1 === true 返回false(严格比较)。所以你每次都得到默认文本。

The parameter which is given to the switch will be compared using ===. In cases which you have, you have expressions which result to boolean type: n==0 || n==1 or n >= 2. When you pass a number , it tries to compare your number with a result given from the expression in cases. So for example with the given number 1 it tries to compare 1 === (1 == 0 || 1 == 1) -> 1 === true which returns false (strict comparison). So you get the Default text every time.

对于第一种情况,你需要在<您的交换机的code>个案,而不是布尔 n == 0 || n == 1 结果为布尔值)。

For the first case, you need to have numbers in the cases of your switch , not a boolean (n==0 || n==1 results to boolean).

对于第二种情况,你在开关中值 true 类型 boolean 。当你再次传递时 1 比较如 true ===(1 == 0 || 1 == 1) - > true === true ,它返回true。因此,您可以根据您的值 n 获得所需的结果。但第二种情况没有使用 true 作为值。如果语句,你可以用替换它。

With the second case, you have in the switch value true of type boolean.When you pass again 1 the comparing goes like true === (1 == 0 || 1 == 1) -> true === true and it returns true. So you get the desired result according to your value n. But the second case has no goals with using true as the value. You can replace it with a if else if statement.

如果你想在很多情况下得到相同的结果你需要在彼此之上写两个案例。看到这个

If you want to get the same result for many cases you need to write 2 cases above each other. See this

case 0:
case 1:
  result

这里的案例类型为 number ,而不是 boolean

Here the cases have type number, not boolean.

代码示例。

function test(n){
    switch (n) {
    case 0:
    case 1:
    console.log("Number is either 0 or 1");
    break;
    case 2:
    console.log("Number is 2")
    break;
    default:
    console.log("Default");}
}

test(0);
test(1);
test(2)

这篇关于为什么Switch语句只能使用true关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆