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

后端 未结 4 1279
余生分开走
余生分开走 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());
    

提交回复
热议问题