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)
当然,较低的两种情况永远不会执行.如果你愿意,你最好只使用if
和else if
语句,或者可能是嵌套开关.
你也可以这样做:
switch (exerciseId + " " + intensity_level) {
case("1 1"): ...
case("1 2"): ...
case("2 1"): ...
case("2 2"): ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30032 次 |
最近记录: |