【问题标题】:Check if the value of object.property is value1 or value2检查 object.property 的值是 value1 还是 value2
【发布时间】:2018-02-13 13:00:49
【问题描述】:

我正在寻找一种解决方案来检查labelKey 属性的值是to_be_rented 还是to_be_put_on_sale

有一个条件我们可以做到:

if (this.project.currentProduct.productStatus.labelKey === ('to_be_rented' || 'to_be_put_on_sale')) {

}

但它不起作用,我也在寻找更复杂的替代方案,例如使用 Lodash 或 es2015。

我该怎么做?

【问题讨论】:

    标签: javascript object ecmascript-6 lodash


    【解决方案1】:

    你的情况是这样的:

    1. 表达式to_be_rented || 的结果to_be_put_on_sale 始终是 to_be_rented
    2. 您将labelKeyto_be_rented 进行比较。

    正确的解决方案是将labelKey 与两个字符串进行比较:

    let labelKey = this.project.currentProduct.productStatus.labelKey;
    if (labelKey === 'to_be_rented' || labelKey === 'to_be_put_on_sale')) {
       ...
    }
    

    使用 ES2016 可以简化:

    let values = ['to_be_rented', 'to_be_put_on_sale'];
    if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
      ...
    }
    

    【讨论】:

      【解决方案2】:

      您可以将所有变体放在一个数组中并使用Array.prototype.indexOf()(甚至在 ES5 中也是如此):

      const variants = ['to_be_rented', 'to_be_put_on_sale'];
      const labelKey = this.project.currentProduct.productStatus.labelKey;
      if (variants.indexOf(labelKey) !== -1) {
        ...
      }
      

      Array.prototype.includes()(在 ES2016 中):

      if (variants.includes(labelKey)) {
        ...
      }
      

      当您有 2 个以上的变体时,这些方法会更方便。

      对于您的情况Array.prototype.indexOf()Array.prototype.includes() 将是相同的,但这些功能之间的区别您可以查看here

      【讨论】:

      • 或者在 ES2016 中使用 ['...', '...'].includes(str)
      【解决方案3】:

      您可以使用数组和Array#includes 来检查该值是否存在于数组中。

      const values = ['to_be_rented', 'to_be_put_on_sale'];
      if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
          // do something
      }
      

      【讨论】:

        【解决方案4】:

        一种时髦的方式:

        var toFind = this.project.currentProduct.productStatus.labelKey;
        if(_.find(['to_be_rented', 'to_be_put_on_sale'], toFind)) {
          // do something
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多