Reputation: 8531
i have a simple array and i want to generate string which include all the elements of the array, for example:
The array is set as follow:
array[0] = uri0
array[1] = uri1
array[2] = uri2
And the output string must be
teststring = uri0,uri1,uri2
I've tried to make this following way (using for loop):
var teststring = "";
teststring = teststring+array[y]
but in the firebug console i see an error message:
"teststring is not defined"
I don't know, what I'm doing wrong. Can someone give me a hint?
Upvotes: 8
Views: 30424
Reputation: 9611
For comma based join, you could use toString() method of Object.prototype (Array object internally inherit it automatically). For other separator based join use join method of the Array object.
var array = [];
array[0] = 'uri0';
array[1] = 'uri1';
array[2] = 'uri2';
console.log(array.toString()); // uri0,uri1,uri2
console.log(array.join(" £ ")); // uri0 £ uri1 £ uri2
Other possible option is implicit type coercion:
// String conversion by implicit coercion
// using '+ operator' and empty string operand ('' , [])
console.log(array + ''); // uri0,uri1,uri2
console.log(array + []); // uri0,uri1,uri2
Upvotes: 0
Reputation:
array.join();
That is the correct answer. If no value is supplied to the join method a comma is the default element separator. Use the following if you don't want any separator at all:
array.join("");
Upvotes: 11
Reputation: 19231
You must use the join function on the array:
var teststring = array.join(",");
Upvotes: 13