Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  134] [ 5]  / answers: 1 / hits: 85396  / 10 Years ago, sun, january 18, 2015, 12:00:00

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

More From » arrays

 Answers
17

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


MDN on Array.join


[#68174] Wednesday, January 14, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shantelc

Total Points: 737
Total Questions: 120
Total Answers: 104

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;