如何将数组转换为不带逗号的字符串,并在没有连接的情况下用空格分隔? [英] How to convert array into string without comma and separated by space in javascript without concatenation?

查看:1677
本文介绍了如何将数组转换为不带逗号的字符串,并在没有连接的情况下用空格分隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,

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


推荐答案

当您在没有传递任何参数的情况下调用 join 时,(逗号)作为默认值, toString 内部调用 join ,不带任何参数被传递。

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 ---------^

Array.join上的MDN

这篇关于如何将数组转换为不带逗号的字符串,并在没有连接的情况下用空格分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆