首页 > 解决方案 > 有没有一种标准的方法来处理 JavaScript 中的选项(可能返回 null 的东西)?

问题描述

是否有在Javascript中返回“选项”(可能为空的对象)的标准方法?

例如,有没有更标准的方法来处理这样的一段代码,尤其是函数GetById(userId)

class User {
  static function GetById(userId) {
    if (userId === 'A_GOOD_ID') {
        return new User('GOOD_NAME');
    }
    return null;
  }

  constructor(name) {
    this.name = name;
  }
}

function authenticate(userId) {
  const user = User.GetById(userId);
  if (user) return true;
  return false;
}

标签: javascript

解决方案


这是标准方式,返回 null 比抛出错误更可取。

使用该函数时,应检查返回值是否为真:

const result = User.GetById(...);
if (!result) {
  // handle error
}

或者您可以使用简写or

User.GetById(...) || handleError();

在许多人看来,它的可读性较差。


推荐阅读