cupakob
cupakob

Reputation: 8531

JavaScript array element to string

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

Answers (4)

SridharKritha
SridharKritha

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

austin cheney
austin cheney

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

mck89
mck89

Reputation: 19231

You must use the join function on the array:

var teststring = array.join(",");

Upvotes: 13

Glenn
Glenn

Reputation: 5342

array.join(",")

Upvotes: 7

Related Questions