javascript - 有没有一种标准的方法来处理 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;
}
解决方案
这是标准方式,返回 null 比抛出错误更可取。
使用该函数时,应检查返回值是否为真:
const result = User.GetById(...);
if (!result) {
// handle error
}
或者您可以使用简写or
:
User.GetById(...) || handleError();
在许多人看来,它的可读性较差。
推荐阅读
- c# - 随机化 3 种颜色
- html - Flexbox 2 divs不同的高度
- .net - “内存压力”是什么意思?
- sql - sqlite INNER JOIN 仅当数据
- laravel - Ngrok / Laravel5 / Homestead - 发布/登录时出现 500 内部服务器错误
- c - 互斥锁和解锁的一些解释
- python - Java 网关进程在向驱动程序发送其端口号之前退出
- c# - C# - 获取当前公共 IP 地址
- matlab - 获取图中连接组件的节点索引(matlab)
- javascript - 如何使用 React JS 将 json api 中的所有值显示到单个下拉列表中?