开发者

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:

"1,2,3,4,5,6"

I need it to be a javascript array with numbers:

[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():

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. 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:

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:

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.

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

Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.

EDIT - i see jQuery has its own map, thats probably worth looking into.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜