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
2 个解决方案
#1
26
When you call join
without any argument being passed, ,
(comma) is taken as default and toString
internally calls join
without any argument being passed.
当你在没有传递任何参数的情况下调用join时,(逗号)被视为默认值,而toString在内部调用join而不传递任何参数。
So, pass your own separator.
所以,传递你自己的分隔符。
var str = array.join(" "); // 'apple tree'
// separator ---------^
Array.join上的MDN
#2
6
pass a delimiter in to join
.
传递分隔符加入。
['apple', 'tree'].join(' '); // 'apple tree'
#1
26
When you call join
without any argument being passed, ,
(comma) is taken as default and toString
internally calls join
without any argument being passed.
当你在没有传递任何参数的情况下调用join时,(逗号)被视为默认值,而toString在内部调用join而不传递任何参数。
So, pass your own separator.
所以,传递你自己的分隔符。
var str = array.join(" "); // 'apple tree'
// separator ---------^
Array.join上的MDN
#2
6
pass a delimiter in to join
.
传递分隔符加入。
['apple', 'tree'].join(' '); // 'apple tree'