【问题标题】:Javascript Simplify conditionJavascript简化条件
【发布时间】:2020-08-29 21:26:09
【问题描述】:

我想请求帮助以简化此条件,因为有重复

if (this.get('fileUrl')) {
      if (this.get('fileContainer.asset_kind') === 'UnsplashAsset') {
        return Asset.create({
          url: this.get('fileUrl'),
          mime_type: this.get('fileContainer.mime_type'),
          isUnsplashObject: true
        });
      } else {
        return Asset.create({
          url: this.get('fileUrl'),
          mime_type: this.get('fileContainer.mime_type'),
          isUnsplashObject: false
        });
      }
    }

【问题讨论】:

    标签: javascript return conditional-statements


    【解决方案1】:

    您可以像这样简单地更新 isUnsplashObject 并返回一个 Asset.create({...}) 像:

    if (this.get('fileUrl')) {
      return Asset.create({
        url: this.get('fileUrl'),
        mime_type: this.get('fileContainer.mime_type'),
        isUnsplashObject: (this.get('fileContainer.asset_kind') === 'UnsplashAsset')
      });
    }
    

    这有点像:

    if (this.get('fileContainer.asset_kind') === 'UnsplashAsset') {
      isUnsplashObject = true
    } else {
      isUnsplashObject = false
    }
    

    或者,使用三元运算符,例如:

    isUnsplashObject = (this.get('fileContainer.asset_kind') === 'UnsplashAsset') ? true : false;
    

    或者,就像 === 相等检查已经返回一个布尔值,所以我们可以简单地只返回它:

    isUnsplashObject = (this.get('fileContainer.asset_kind') === 'UnsplashAsset')
    

    【讨论】:

      【解决方案2】:

      唯一改变的是UnsplashObject,所以把条件放在那里。

      if (this.get('fileUrl')) {
          return Asset.create({
              url: this.get('fileUrl'),
              mime_type: this.get('fileContainer.mime_type'),
              isUnsplashObject: this.get('fileContainer.asset_kind') === 'UnsplashAsset'
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-11
        • 2020-02-12
        • 2021-07-17
        • 2021-05-03
        • 2012-06-03
        相关资源
        最近更新 更多