Javascript 如何在没有连接的情况下将数组转换为没有逗号的字符串并在javascript中用空格分隔?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28007949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:06:41  来源:igfitidea点击:

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

javascriptarraysstring

提问by tlaminator

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 elements separated by commas. For example,

我知道你可以通过循环遍历数组元素和连接来做到这一点。但我正在寻找单线解决方案。toString() 和 join() 返回以逗号分隔元素的字符串。例如,

var array = ['apple', 'tree'];
var toString = array.toString()    # Will return 'apple,tree' instead of 'apple tree', same for join() method

回答by Amit Joki

When you call joinwithout any argument being passed, ,(comma) is taken as default and toStringinternally calls joinwithout any argument being passed.

当您在join不传递任何参数的,情况下toString调用时,(逗号) 被视为默认值,并且在join不传递任何参数的情况下进行内部调用。

So, pass your own separator.

所以,通过你自己的分隔符。

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

MDN on Array.join

Array.join 上的 MDN

回答by Cheezmeister

pass a delimiter in to join.

将分隔符传递给join.

['apple', 'tree'].join(' '); // 'apple tree'

回答by Seyi Oluwadare

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

使用 Array.join() 方法。修剪以删除任何不必要的空格。

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

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

回答by Richie Bendall

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

最简单的方法是使用.join(' ').

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

但是,如果 Array 包含零长度对象,例如null,以下代码将避免多个空格:

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

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());