2

I am trying to convert a comma separated string into an array using the split method(Convert comma separated string to array).

This is the code:

var nameList = "milk,sugar,flour";
var nameArray = nameList.split(',');

document.write('The nameList is: ' + nameList);
document.write('<br />');
document.write('The nameArray is: ' + nameArray);

This is the output:

The nameList is: milk,sugar,flour
The nameArray is: milk,sugar,flour

It looks to me like it is still a string separated by commas. Why is the comma-separated string not converting to an array using split() in javaScript?

Community
  • 1
  • 1
zeckdude
  • 15,877
  • 43
  • 139
  • 187

3 Answers3

6

It's an array. Array#toString produces the comma-separated output.

Try this:

[3, 4, 'b'].toString(); 

If you use console.log instead of document.write to inspect nameArray, you'll see that it is an array.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
0

thats the way how JAVASCRIPT shoes an array

it did convert it

but you told JS to display it

so thats what he does.

proof:

nameArray[0]====>milk

nameArray[1]====>sugar
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

When you implicitly convert the array to a string by appending it to a string, it displays the array.toString() which uses commas. You can override this if you want.

if you do this instead, it will show the properly annotated version.

 JSON.stringify( nameArray ,"\t")
FlavorScape
  • 13,301
  • 12
  • 75
  • 117