javascript - TypeScript 中的 switch 语句损坏
问题描述
我在 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");
解决方案
这不是 switch 语句的工作方式。
如果你要写:
switch (true) {
case todoList:
if (todoList.length >= 5) { //todoList is null???
console.log("LIST IS FULL!");
}
break;
}
它会起作用,因为在 switch 语句中,您正在检查情况是否为真。
Switch 语句采用原始值,例如布尔值、字符串、数字等。
您尝试使用 switch 语句的方式更复杂,并且只能与 if 语句一起使用。
推荐阅读
- asp.net-core - 将多个网站指向同一个 Asp.Net Identity 用户数据库是否安全?
- javascript - Array.find() 方法在 TypeScript 中与 req.param 一起使用
- sublimetext3 - 包名中的空格
- jsf - 具有唯一 id 2 个成员变量元组的对象列表的转换器
- javascript - 如何在 javascript 数组中编写 html 的锚元素?
- r - 如何删除此 csv 文件中包含某些字符串的行
- javascript - 在 JavaScript 中检查两个数组的值是否相同/相等的最佳方法
- c++ - 我在使用带有静态成员函数的 operator= 重载时遇到问题。代码有问题吗?
- typescript - 实现泛型类型时缺少提示“实现接口 X”
- java - BouncyCastle 如何生成 ECDH“密钥”?