How to convert array into string without comma and separated by space in javascript without concatenation?

后端 未结 4 1264
余生分开走
余生分开走 2020-12-03 06:53

I know you can do this through looping through elements of array and concatenating. But I\'m looking for one-liner solutions. toString() and join() returns string with eleme

相关标签:
4条回答
  • 2020-12-03 07:07

    The easiest way is to use .join(' ').

    However, if the Array contains zero-length objects like null, the following code would avoid multiple spaces:

    arr.filter(i => [i].join(" ").length > 0).join(" ");

    Here's some example usage:

    Array.prototype.merge = function(char = " ") {
      return this.filter(i => [i].join(" ").length > 0).join(char);
    };
    
    console.log(["a", null, null, "b"].merge());
    
    0 讨论(0)
  • 2020-12-03 07:11

    When you call join without any argument being passed, ,(comma) is taken as default and toString internally calls join without any argument being passed.

    So, pass your own separator.

    var str = array.join(' '); //'apple tree'
    // separator ---------^
    

    MDN on Array.join

    0 讨论(0)
  • 2020-12-03 07:14

    pass a delimiter in to join.

    ['apple', 'tree'].join(' '); // 'apple tree'
    
    0 讨论(0)
  • 2020-12-03 07:14

    Use the Array.join() method. Trim to remove any unnecessary whitespaces.

    var newStr = array.join(' ').trim()

    0 讨论(0)
提交回复
热议问题