How can I convert a string to a JavaScript array?
Look at the code:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1
Is there any chance to convert such string into a JavaScript array?
For simple array members like that, you can use
JSON.parse.This gives you an Array of numbers.
If you use
.split(), you’ll end up with an Array of strings.Just be aware that
JSON.parsewill limit you to the supported data types. If you need values likeundefinedor functions, you’d need to useeval(), or a JavaScript parser.If you want to use
.split(), but you also want an Array of Numbers, you could useArray.prototype.map, though you’d need to shim it for IE8 and lower or just write a traditional loop.