如何在ReactNative中检查嵌套变量的可用性而不检查前面所有变量的可用性?

问题描述 投票:0回答:1

例如,在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() }

或类似的东西?

谢谢。

javascript react-native optional
1个回答
0
投票

您可以使用递归实用程序功能来测试每个路径段的存在:

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’)) { ... }
© www.soinside.com 2019 - 2024. All rights reserved.