views:

6853

answers:

3

I have a one-dimensional array of strings in Javascript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety Javascript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)

+14  A: 

The join function:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr.join(","));
Wayne
+3  A: 

Or (more efficiently):

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr); // same as document.write(arr.toString()) in this context

The toString method of an array when called returns exactly what you need - comma-separated list.

Sergey Ilinsky
+1  A: 

Actually, the toString() implementation does a join with commas by default:

var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto

I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

Ates Goral