javascript - 将嵌套的 else if 语句转换为 JavaScript 中的 switch 语句

标签 javascript typescript ecmascript-6

我有以下带有嵌套 (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/

相关文章:

javascript - 发布带有新行的推文

javascript - 通过在前端单击来停止 Node.js 中的功能

javascript - React 16.0.0 父子孙子。更新 Parent 中的状态不会更新 GrandChild

typescript - 我如何决定 @types/* 是进入 `dependencies` 还是 `devDependencies` ?

javascript - babel 与express js :avoid relative path imports

javascript - 在具有 maxLength 的 JSON 模式中将属性设置为 "string"或 null

javascript - jquery.js 未在 Perl 模板工具包生成的文件中正确引用

angular - 如何从 Visual Studio 2015 中的非相对路径导入模块

javascript - 在 react 中导入多个文件

TypeScript + ES6 Map + 对象类型的索引签名隐式具有 'any' 类型