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

如何检查所有参数是否相等并返回字符串

  •  0
  • physicsboy  · 技术社区  · 8 年前

    我想将传入函数的参数(所有字符串)与分隔符“|”连接起来,但如果它们都是空字符串,则只传递一个空字符串。

    我有以下几点:

    constructString(one: string, two: string, three: string) {
      if (one === '' && two === '' && three === '') {
        return '';
      }
      return [one, two, three].filter(Boolean).join('|')
    }
    

    我的问题是。。。有没有一种更简单、更优雅的方法来执行这项任务,或者JS有一些有用的功能,而为了执行这项任务,我缺少这些功能?

    4 回复  |  直到 8 年前
        1
  •  2
  •   Orelsanpls    8 年前

    ... 操作人员

    function constructString(...args) {
      if (args.every(x => x === '')) {
         return '';
      }
      
      return args.join('|');
    }
    
    console.log('[', constructString('a', 'b', 'c'), ']');
    
    console.log('[', constructString('', '', ''), ']');

    function constructString(...args) {
      return args.every(x => x === '') ? '' : args.join('|');
    }
    
    console.log('[', constructString('a', 'b', 'c'), ']');
    
    console.log('[', constructString('', '', ''), ']');
        2
  •  0
  •   Ankit Agarwal    8 年前

    您只需使用 filter Boolean 在筛选出空值时也适用于空值的值。

    function constructString(one, two, three) {
      
      return [one, two, three].filter(Boolean).join('|')
    }
    //with Boolean values as string
    console.log(constructString('true', 'false', 'true'));
    
    //with blank values as string
    console.log(constructString('', '', ''));
        3
  •  0
  •   brk    8 年前

    您可以使用arguments对象并从中创建数组,并检查它们是否都是 '' Array.every 它将返回真或假。如果全部为空,则返回

    否则是参数包含空字符串和非空字符串的混合,然后过滤掉空字符串并用分隔符连接

    function constructString() {
      let crtArry = Array.from(arguments).every(function(item) {
        return item === '';
      });
      if (crtArry) {
        return 'Returning empty String' + '';
      } else {
        return Array.from(arguments).filter((item) => {
          return item !== '';
        }).join('|')
      }
    }
    
    console.log(constructString('', '', ''))
    console.log(constructString('2', '3', ''))
        4
  •  0
  •   Orelsanpls    8 年前

    试试这个

    function constructString(one, two, three) {
      if (one === '' && two === '' && three === '') {
        return '';
      }
      return [one, two, three].filter(Boolean).join('|')
    }
    
    console.log('result :',constructString('String-1','String-1','String-1'));
    推荐文章