带有逻辑和的打字稿开关盒 [英] Typescript switch case with logical and

查看:28
本文介绍了带有逻辑和的打字稿开关盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 switch 语句,但它似乎没有我想要的那样工作.

I am trying to write a switch statement but it doesn't seem to work how I want.

getExerciseDescription(exerciseId, intensity_level){

    alert(exerciseId + " " + intensity_level)

    switch (exerciseId && intensity_level) {
        case (1 && 1):
        this.header="Exercise 1 Level 1";
        this.instructions="Exercise 1 Level 1";
        break;
        case (1 && 2):
        this.header="Exercise 1 Level 2";
        this.instructions="Exercise 1 Level 2";
        break;  


        case (2 && 1):
        this.header="Exercise 2 Level 1";
        this.instructions="Exercise 2 Level 1";
        break;  
        case (2 && 2):
        this.header="Exercise 2 Level 2";
        this.instructions="Exercise 2 Level 2";
        break;

        default:
        this.header="Default";
        this.instructions="Default";
        break;
    }

    return new Popup(this.header, this.instructions);
} 

警报给出 2 和 1,但返回的值是 (1 && 1).为什么会这样?我该如何解决这个问题?

The alerts gives 2 and 1 but the returned value is for (1 && 1). Why is it so? How can I fix this?

推荐答案

你不能像那样使用 switch.(1 && 1) == (2 && 1) == 1(1 && 2) == (2 && 2)== 2,所以你做的相当于:

You just can't use a switch like that. (1 && 1) == (2 && 1) == 1 and (1 && 2) == (2 && 2) == 2, so you're doing the equivalent of:

getExerciseDescription(exerciseId, intensity_level){

    alert(exerciseId + " " + intensity_level)

    switch (exerciseId && intensity_level) {
        case (1):
        this.header="Exercise 1 Level 1";
        this.instructions="Exercise 1 Level 1";
        break;
        case (2):
        this.header="Exercise 1 Level 2";
        this.instructions="Exercise 1 Level 2";
        break;  


        case (1):
        this.header="Exercise 2 Level 1";
        this.instructions="Exercise 2 Level 1";
        break;  
        case (2):
        this.header="Exercise 2 Level 2";
        this.instructions="Exercise 2 Level 2";
        break;

        default:
        this.header="Default";
        this.instructions="Default";
        break;
    }

    return new Popup(this.header, this.instructions);
} 

所以当然下面两种情况永远不会执行.您最好只使用 ifelse if 语句,或者如果需要,也可以使用嵌套开关.

So of course the lower two cases will never execute. You're better of just using if and else if statements, or maybe nested switches if you want.

您还可以执行以下操作:

You could also do something like:

switch (exerciseId + " " + intensity_level) {
    case("1 1"): ...
    case("1 2"): ...
    case("2 1"): ...
    case("2 2"): ...

这篇关于带有逻辑和的打字稿开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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