【问题标题】:How to know if an array is Empty?如何知道数组是否为空?
【发布时间】:2019-12-20 19:15:34
【问题描述】:

我正在从 API 传递一个数组,并想知道该数组是否为空,以打印错误消息。

查看不同的站点,它们都没有工作。

      {this.props.items ? errorMessage : <h1>Working</h1>}

【问题讨论】:

标签: reactjs


【解决方案1】:

你可以使用length属性

  {this.props.items.length == 0 ? errorMessage : <h1>Working</h1>}

【讨论】:

  • @Martin hah 我可以替换为“向上箭头”
【解决方案2】:

this.props.items &amp;&amp; this.props.items.length &gt; 0 ? &lt;h1&gt;Working&lt;/h1&gt; : errorMessage

【讨论】:

    【解决方案3】:

    先检查天气数组是否存在然后检查数组的长度是否大于0,总是使用双重否定将该数组转换为布尔类型

    {!!this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage}
    

    【讨论】:

      【解决方案4】:

      检查lodash 库。对这种需求很有帮助。

      https://lodash.com/docs/4.17.15#isEmpty

      有了这个,你可以使用:

      {isEmpty(this.props.items) ? errorMessage: &lt;h1&gt;Working&lt;/h1&gt;}

      【讨论】:

        【解决方案5】:

        在检查长度之前检查类型更安全,因为类型 string 也可以返回长度

        { Array.isArray(this.props.items) && this.props.items.length < 1 ? errorMessage : <h1>Working</h1> }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-15
          • 1970-01-01
          相关资源
          最近更新 更多