代码之家  ›  专栏  ›  技术社区  ›  user13286

可以使用这样的速记条件构建字符串吗?

  •  1
  • user13286  · 技术社区  · 7 年前

    我正在尝试根据下拉选择向我的URL添加一些参数,我希望代码尽可能简短,因此我正在尝试为参数构建一个字符串,该字符串省略任何空白变量,以便它们不会附加到URL字符串。以下是我尝试过的:

    $(function() {
      var product = 'shirt',
          size = 'large',
          color = 'blue',
          custom = '';
          
      var urlParams = (product === '') ? '' : 'product=' + product + '&' + (size === '') ? '' : 'size=' + size + '&' + (color === '') ? '' : 'color=' + color + '&' + (custom === '') ? '' : 'custom=' + custom;
      
      console.log(urlParams);
      
      // Go to results page
      // location.href = 'results?' + urlParams;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    urlParams 是:

    product=shirt&size=large&color=blue
    

    3 回复  |  直到 7 年前
        1
  •  1
  •   Praveen Kumar Purushothaman    7 年前

    偏执狂很重要!

    问题是,你没有研究那些老的。这个 custom === "" 变得真实,然后你的整个状况就崩溃了。更好的方法是:

    (function() {
      var product = 'shirt',
        size = 'large',
        color = 'blue',
        custom = '';
    
      var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);
    
      console.log(urlParams);
    
      // Go to results page
      // location.href = 'results?' + urlParams;
    })();

    &

    (function() {
      var product = 'shirt',
        size = 'large',
        color = 'blue',
        custom = '';
    
      var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);
      urlParams = urlParams.replace(/^\&+|\&+$/g, '');
      console.log(urlParams);
    
      // Go to results page
      // location.href = 'results?' + urlParams;
    })();

    最好是使用数组和 .join()

    (function() {
      var product = 'shirt',
        size = 'large',
        color = 'blue',
        custom = '';
    
      var urlParams = [
        ((product === '') ? '' : 'product=' + product),
        ((size === '') ? '' : 'size=' + size),
        ((color === '') ? '' : 'color=' + color),
        ((custom === '') ? '' : 'custom=' + custom)
      ];
      urlParams = urlParams.join("&").replace(/^\&+|\&+$/g, '');
      console.log(urlParams);
    
      // Go to results page
      // location.href = 'results?' + urlParams;
    })();
        2
  •  1
  •   Nina Scholz    7 年前

    您可以检查该值,并对格式化字符串采用逻辑and。

    var urlParams = (product && 'product=' + product + '&') +
                    (size && 'size=' + size + '&') +
                    (color && 'color=' + color + '&') +
                    (custom && 'custom=' + custom);
    

    一种方法是使用对象,过滤真实值,并用模板字符串构建格式化字符串。

    function getString(object) {
        return Object
            .entries(object)
            .filter(([, v]) => v)
            .map(([k, v]) => `${k}=${v}`)
            .join('&');
    }
    
    var product = 'foo', 
        size = '42',
        color = '',
        data = { product, size, color };
        
        
    console.log(getString(data))
        3
  •  0
  •   user10616833 user10616833    7 年前

    const params = {
        product: 'shirt',
        size: 'large',
        color: '',
        custom: null
    }
    const valid = p => k => typeof p [k] === 'string' && p [k].length > 0
    let queryString = Object.keys (params).filter (valid (params)).map (k => `${k}=${params[k]}`).join ('&')
    
    console.log (queryString)