为什么 Switch 语句仅适用于 true 关键字? [英] Why Switch statement only working with true keyword?

查看:18
本文介绍了为什么 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==1n >= 2.当您传递一个 number 时,它会尝试将您的 number 与 case 表达式给出的结果进行比较.例如,对于给定的数字 1 它会尝试比较 1 === (1 == 0 || 1 == 1) -> 1 === true 返回 false(严格比较).所以你每次都会得到 Default 文本.

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.

对于第一种情况,您需要在 switch 的 cases 中有数字,而不是 boolean (n==0 || n==1 结果为 boolean).

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).

对于第二种情况,你有 boolean 类型的开关值 true.当你再次传递 1 时,比较就像 true === (1 == 0 || 1 == 1) -> true === true 它返回 true.所以你根据你的值 n 得到想要的结果.但是第二种情况没有使用 true 作为值的目标.您可以将其替换为 if else if 语句.

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.

如果您想在多个案例中获得相同的结果,您需要将 2 个案例放在一起.看到这个

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

这里的 case 类型是 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天全站免登陆