Home > Article > Web Front-end > How to Convert a String with Commas to an Array in JavaScript?
Converting String with Commas to Array in JavaScript
Converting a string such as "0,1" to a JavaScript array can be challenging. Let's address the code example provided:
var string = "0,1"; var array = [string]; alert(array[0]);
In this scenario, 'alert(array[0])' displays "0,1". To obtain the desired result of an array, we need to convert the string.
Solution Using JSON.parse:
For simple array members, JSON.parse can be leveraged:
var array = JSON.parse("[" + string + "]");
This approach yields an array of numbers:
[0, 1]
Alternative Solution Using .split():
If you prefer to use .split(), you'll obtain an array of strings:
var array = string.split(",");
["0", "1"]
Considerations for Alternative Solution:
Note that .split() can't handle complex data types like undefined or functions. In such cases, eval() or a JavaScript parser is required.
To convert the split strings to numbers, you can utilize Array.prototype.map:
var array = string.split(",").map(Number);
This returns an array of numbers:
[0, 1]
To support Array.prototype.map in older browsers, consider shimming it or using a traditional loop.
The above is the detailed content of How to Convert a String with Commas to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!