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?
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.
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
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.