javascript - 如何在 ReactNative 中检查嵌套变量的可用性而不检查所有前面的变量可用性?
问题描述
例如,在 iOS Swift 中,我可以这样做:
if (self.user?.company?.pic?.phoneNumber != null) { doSomething() }
无需:
if (self.user != null && self.user!.company != null && self.user!.company!.pic != null && self.user!.company!.pic!.phoneNumber != null) { doSomething() }
在 ReactNative(或 Javascript)中,我发现如果一个对象未定义,我无法检查其中是否存在变量,所以我必须先检查对象是否未定义,然后才能安全地检查其中的变量是否未定义。
if (typeof this.state.user !== "undefined" && typeof this.state.user.company !== "undefined" && typeof this.state.user.company.pic !== "undefined" && typeof this.state.user.company.pic.phoneNumber !== undefined) { this.doSomething() }
我怎样才能把它变成:
if (typeof this.state.user.company.pic.phoneNumber !== "undefined") { this.doSomething() }
或类似的东西?
谢谢。
解决方案
如果您不能使用仍然是一个提议但可通过babel 插件使用的可选链接,您可以使用递归实用程序函数来测试每个路径段的存在:
const pluck = (item, path) => {
const [, part, rest] = /^([^.]+)\.*(.*)/.exec(path) || [];
if (!part) {
return null;
}
const o = (item || {})[part];
if (o == null) {
return null;
}
return rest.length ? pluck(o, rest) : o;
};
if (pluck(this.state, ‘user.company.pic.phoneNumber’)) {
doSomething();
}
推荐阅读
- javascript - 如何防止 Angular 在生产模式下删除查询参数?
- google-apps-script - Gmail 脚本 - 添加和删除标签的标签
- c - 调试断言失败:使用 CLion 在 C 中读取文件
- python-3.x - 如何构建流程树?
- npm - 如何找到尝试在启动时创建错误目录的 NPM 的配置
- c - 我的项目每次都有不同的结果
- python - 组合两个 if 语句时出现 TypeError 问题
- excel - 使用封闭 XML 导出 .xlsx/.xls
- amazon-web-services - 创建 ec2 实例时播放的 ansible 未定义变量
- amazon-web-services - 在 AWS Athena 中创建存储桶表