How to Convert a String with Commas into a JavaScript Array
The code:
var string = "0,1"; var array = [string]; alert(array[0]);
shows a problem when trying to convert a string with commas into a JavaScript array. The alert shows "0,1" instead of "0" as desired.
To resolve this, you can use JSON.parse to convert the string into an array of numbers:
var array = JSON.parse("[" + string + "]");
This will give you the expected result:
[0, 1]
Note that using .split() will result in an array of strings:
["0", "1"]
JSON.parse has limitations regarding supported data types. If you need to work with undefined values or functions, you may need to consider using eval() or a JavaScript parser.
For more flexibility, you can also use .split() with Array.prototype.map to convert the strings to numbers:
var array = string.split(",").map(Number);
This will again give you the desired result:
[0, 1]
Keep in mind that this approach requires a shim for IE8 and lower versions, or you can use a traditional loop instead of Array.prototype.map.
The above is the detailed content of How to Convert a String with Commas into a JavaScript Array of Numbers?. For more information, please follow other related articles on the PHP Chinese website!