带有逻辑和的打字稿开关案例

Thi*_*ker 8 javascript switch-statement typescript

我正在尝试编写一个switch语句,但它似乎没有按我的意愿工作.

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);
} 
Run Code Online (Sandbox Code Playgroud)

警报给出2和1,但返回值为(1 && 1).为什么会这样?我怎样才能解决这个问题?

Cha*_*ton 11

你就是不能用switch那样的.(1 && 1) == (2 && 1) == 1而且(1 && 2) == (2 && 2) == 2,你做的相当于:

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);
} 
Run Code Online (Sandbox Code Playgroud)

当然,较低的两种情况永远不会执行.如果你愿意,你最好只使用ifelse if语句,或者可能是嵌套开关.

你也可以这样做:

switch (exerciseId + " " + intensity_level) {
    case("1 1"): ...
    case("1 2"): ...
    case("2 1"): ...
    case("2 2"): ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,比较字符串而不是数字会导致性能下降。尽管字符串长度为 3,但它可能不会产生任何明显的影响 - 请参阅http://stackoverflow.com/a/23837610/6806381 (2认同)