Convert string with commas to array

2022-08-29 23:21:40

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 shows . If it where an array, it would show . And if is called, it should pop-up alert0,10alert(array[1])1

Is there any chance to convert such string into a JavaScript array?


答案 1

For simple array members like that, you can use .JSON.parse

var array = JSON.parse("[" + string + "]");

This gives you an Array of numbers.

[0, 1]

If you use , you'll end up with an Array of strings..split()

["0", "1"]

Just be aware that will limit you to the supported data types. If you need values like or functions, you'd need to use , or a JavaScript parser.JSON.parseundefinedeval()


If you want to use , but you also want an Array of Numbers, you could use , though you'd need to shim it for IE8 and lower or just write a traditional loop..split()Array.prototype.map

var array = string.split(",").map(Number);

答案 2

Split it on the character;,

var string = "0,1";
var array = string.split(",");
alert(array[0]);