Converting Comma-Separated String to Array in JavaScript
When attempting to convert a comma-separated string to a JavaScript array using the code snippet provided, the resulting array remains as a string rather than an array of separate elements.
To effectively achieve this conversion, JSON.parse() can be utilized. By wrapping the string in square brackets, JSON.parse() interprets it as an array.
var string = "0,1"; var array = JSON.parse("[" + string + "]");
This results in an array of numbers:
[0, 1]
Alternatively, .split() can be employed to create an array of strings.
var array = string.split(",");
Output:
["0", "1"]
It's important to note that JSON.parse() restricts the data types to supported ones. If values like undefined or functions are required, eval() or a JavaScript parser will be necessary.
For instances where .split() is used and an array of numbers is desired, Array.prototype.map can be applied, although it might require a shim for IE8 and below or a traditional loop.
var array = string.split(",").map(Number);
The above is the detailed content of How to Convert a Comma-Separated String to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!