JavaScript array element for string

I have a simple array and I want to generate a string that includes all the elements of the array, for example:

The array is set as follows:

array[0] = uri0
array[1] = uri1
array[2] = uri2

And the output line should be

teststring = uri0,uri1,uri2

I tried to do it as follows (using for loop):

var teststring = "";
teststring = teststring+array[y]

but in the firebug console I see an error message:

"teststring is not defined"

I do not know what I am doing wrong. Can someone give me a hint?

+5
source share
4 answers

You should use the join function in the array:

var teststring = array.join(",");
+9
source
array.join();

. , . , :

array.join("");
+11
array.join(",")
+7

toString() Object.prototype ( Array ). join Array.

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
Hide result

- :

// String conversion by implicit coercion
// using '+ operator' and empty string operand ('' , [])
console.log(array + ''); // uri0,uri1,uri2
console.log(array + []); // uri0,uri1,uri2
Hide result
0

All Articles