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

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

问题描述

我知道你可以通过循环遍历数组元素并连接来做到这一点.但我正在寻找单线解决方案.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 而没有传递任何参数时,,(comma) 被作为默认值,并且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

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

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