我在 TypeScript 中遇到 switch 语句的问题在多个代码编辑器上尝试过,我正在尝试使用 switch (true) 但由于某种原因代码在 switch 语句中失败。const todoList: string[] | null = [];function pushItemToTodoList(item: string) { //COMPILES!! if (todoList !== undefined && todoList !== null && todoList.length) { if (todoList.length >= 5) { console.log("LIST IS FULL!"); } } //DOESN'T COPMILE!! switch (true) { case todoList !== undefined && todoList !== null && todoList.length: if (todoList.length >= 5) { //todoList is null??? console.log("LIST IS FULL!"); } break; }}pushItemToTodoList("clean house");
2 回答
![?](http://img1.sycdn.imooc.com/545850a00001fdd002200220-100-100.jpg)
Helenr
TA贡献1780条经验 获得超4个赞
switch 语句本身不会失败。它很简单,不能容忍带有变量的 case 语句。也不是条件运算符,只有静态值。在编译时,switch 语句会构建 case 语句中所有静态值及其跳转位置的索引。不能在 case 语句中使用变量,因为在编译时,这些变量不应该被计算甚至不存在。Switch - Case 语句的性能非常好,因为带有静态值和跳转位置的索引是预编译的。不过,有一种方法可以解决这个特定问题,即在 switch 语句中将布尔逻辑与代数相结合,在 case 语句中将静态值结合起来。
![?](http://img1.sycdn.imooc.com/545847d40001cbef02200220-100-100.jpg)
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
这不是 switch 语句的工作方式。
如果你会写:
switch (true) {
case todoList:
if (todoList.length >= 5) { //todoList is null???
console.log("LIST IS FULL!");
}
break;
}
它会起作用,因为在 switch 语句中您正在检查情况是否为真。
Switch 语句采用原始值,例如布尔值、字符串、数字等。
您尝试使用 switch 语句的方式更复杂,并且只能使用 if 语句。
添加回答
举报
0/150
提交
取消