[英]Elegant way to convert string of values into a Javascript array?
I have an ajax request that returns a list of values like this: 我有一个ajax请求,返回如下的值列表:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers: 我需要它是一个带数字的javascript数组:
[1,2,3,4,5,6]
I tried: 我试过了:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output: 但数字仍然是输出中的字符串:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? 是否有一种干净的方式将其作为编号数组? Preferably without writing a function to iterate through it?
最好不编写函数来迭代它?
You need to loop through and convert them to numbers, like this: 你需要循环并将它们转换为数字,如下所示:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example: 或者,更传统的例子:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
A more jQuery-centric approach using jQuery.map() : 使用jQuery.map()的更多以jQuery为中心的方法:
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
Not sure if this counts as writing a function but you can use the map function in jquery. 不确定这是否算作编写函数,但您可以在jquery中使用map函数。 I saw you listed as a tag so I assume you are using:
我看到你列为标签,所以我假设你正在使用:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});
// jquery must have a way to do what any modern browser can do: // jquery必须有办法完成现代浏览器可以做的事情:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers
If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval
: 如果您信任ajax响应,并且(无论出于何种原因)您承诺不使用循环,则可以始终使用
eval
:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");
If you don't wish to expliclty iterate you can use array.map
, javascripts map function. 如果你不希望expliclty迭代你可以使用
array.map
,javascripts map函数。
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site. 这可能是一个更好的参考,但我不是我们javascript足够有一个很好的参考网站。
EDIT - i see jQuery has its own map, thats probably worth looking into. 编辑 - 我看到jQuery有自己的地图,这可能值得研究。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.