例如,在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() }
或类似的东西?
谢谢。
您可以使用递归实用程序功能来测试每个路径段的存在:
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’)) { ... }