我有以下带有嵌套 (if) else if 语句的端点
@Patch("/games/:id")
@HttpCode(200)
async updateGame(@Param("id") id: number, @Body() update: Partial<Game>) {
const updatedGame = await Game.findOne(id);
if (!updatedGame) {
throw new NotFoundError("HTTP 404 Not Found: No Games Here");
} else if (update.color && !validColor(update.color)) {
throw new BadRequestError("HTTP 400 Bad Request: No Such Color");
} else if (
update.board !== undefined &&
moves(update.board, updatedGame.board) > 1
) {
throw new BadRequestError(
"HTTP 400 Bad Request: Only one move allowed. Wait your turn"
);
} else {
console.log("Game has been updated");
return Game.merge(updatedGame, update).save();
}
}
我想将其转换为 switch 语句 为了可读性 我尝试了几次 但不知何故,常量变量的值没有被读取。
以下是我尝试替换 else if 列表的 switch 语句
switch(updatedGame){
case (!updatedGame):
throw new NotFoundError("HTTP 404 Not Found: No Games Here")
case(update.color && !validColor(update.color)):
throw new BadRequestError("HTTP 400 Bad Request: No Such Color")
case(update.board !== undefined && moves(update.board, updatedGame.board) > 1):
throw new BadRequestError("HTTP 400 Bad Request: Only one move allowed. Wait your turn")
default : console.log("Game has been updated");
Game.merge(updatedGame, update).save();
}
if else if 列表正常工作 但是 switch 语句给出了错误
最佳答案
为了更好的可读性,您可以省略 else 部分,因为抛出的异常(未在函数内部捕获)会结束函数。
if (!updatedGame) {
throw new NotFoundError("HTTP 404 Not Found: No Games Here");
}
if (update.color && !validColor(update.color)) {
throw new BadRequestError("HTTP 400 Bad Request: No Such Color");
}
if (update.board !== undefined && moves(update.board, updatedGame.board) > 1) {
throw new BadRequestError("HTTP 400 Bad Request: Only one move allowed. Wait your turn");
}
console.log("Game has been updated");
return Game.merge(updatedGame, update).save();
关于javascript - 将嵌套的 else if 语句转换为 JavaScript 中的 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226275/