将带逗号的字符串转换为数组 [英] Convert string with commas to array
问题描述
如何将字符串转换为 JavaScript 数组?
How can I convert a string to a JavaScript array?
看代码:
var string = "0,1";
var array = [string];
alert(array[0]);
在这种情况下,alert
会弹出一个 0,1
.是数组时,弹出0
,调用alert(array[1]);
时,弹出>1
.
In this case, alert
would pop-up a 0,1
. When it would be an array, it would pop-up a 0
, and when alert(array[1]);
is called, it should pop-up the 1
.
有没有办法把这样的字符串转换成 JavaScript 数组?
Is there any chance to convert such string into a JavaScript array?
推荐答案
对于这样的简单数组成员,您可以使用 JSON.parse
.
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]
如果你使用 .split()
,你会得到一个字符串数组.
If you use .split()
, you'll end up with an Array of strings.
["0", "1"]
<小时>
请注意,JSON.parse
会将您限制为支持的数据类型.如果您需要像 undefined
或函数这样的值,则需要使用 eval()
或 JavaScript 解析器.
Just be aware that JSON.parse
will limit you to the supported data types. If you need values like undefined
or functions, you'd need to use eval()
, or a JavaScript parser.
如果你想使用 .split()
,但你也想要一个数字数组,你可以使用 Array.prototype.map
,尽管你需要为 IE8 及更低版本填充它,或者只是编写一个传统的循环.
If you want to use .split()
, but you also want an Array of Numbers, you could use Array.prototype.map
, though you'd need to shim it for IE8 and lower or just write a traditional loop.
var array = string.split(",").map(Number);
这篇关于将带逗号的字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!