8

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?

4 Answers 4

13

You must use the join function on the array:

var teststring = array.join(",");
Sign up to request clarification or add additional context in comments.

Comments

11
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("");

1 Comment

Like the default explanation. Shows more in depth knowledge
7
array.join(",")

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.