【问题标题】:JavaScript/Angular1 - Refacto algo/logic conditionJavaScript/Angular1 - 重构算法/逻辑条件
【发布时间】:2017-10-11 09:27:57
【问题描述】:

我有 2 个条件来比较 2 个模型是否存在以显示不同的消息。 对象this.realEstateProjectCurrentProduct保持不变,只是属性housingTaxpropertyTax不同,else的大小写保持不变。

if (this.realEstateProjectCurrentProduct.housingTax) {
  return this.housingTax = `${this.realEstateProjectCurrentProduct.housingTax} ${this.$translate.instant('currencySymbols.euro')}`
} else {
  return this.housingTax = 'No data'
}
if (this.realEstateProjectCurrentProduct.propertyTax) {
  return this.propertyTax = `${this.realEstateProjectCurrentProduct.propertyTax} ${this.$translate.instant('currencySymbols.euro')}`
} else {
  return this.propertyTax = 'No data'
}

我该如何改善这两个条件,因为它们与 Lodash 或 ecmaScript 2015 有太多相似之处

【问题讨论】:

  • 上面的代码永远不会进入第二个 if 语句,因为你在赋值之前有所有的 return 语句

标签: javascript angularjs ecmascript-6 lodash


【解决方案1】:

你可以使用属性解构,例如:

let { housingTax, propertyTax } = this.realEstateProjectCurrentProduct;
housingTax = housingTax ? `${housingTax} ${this.$translate.instant('currencySymbols.euro')}`: 'no data'
propertyTax = propertyTax ?  `${propertyTax} ${this.$translate.instant('currencySymbols.euro')}` : 'no data'

【讨论】:

    【解决方案2】:

    虽然不是最安全的方法(魔术字符串通常不好),但您可以尝试提取实际功能并传入您要更改的属性的名称。

    function processTax(taxType) {
      if (this.realEstateProjectCurrentProduct[taxType]) {
        this[taxType]= `${this.realEstateProjectCurrentProduct[taxType]} ${this.$translate.instant('currencySymbols.euro')}`
      } else {
        this[taxType]= 'No data'
      }
    }
    
    processTax('housingTax');
    processTax('propertyTax');
    

    如果您希望将来有更多,请考虑使用数组:

    ['housingTax', 'propertyTax'].forEach(tax => processTax(tax));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2014-06-20
      • 2010-10-02
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多