Reputation: 745
["57300","730","17300","17330","17340","70","220","320","380","420","340","130","50","280","360","550","43110","44340","400","620","440","20","72850"]
Is an array of strings being passed back into a javascript function which proceeds to do work on it to break it up into an array of strings (using the split function with "," as a delimiter).
The problem here, is I need to convert each of those after that into an integer. Sounds easy okay.
So I proceed to do a:
$.each(data, function(i, item)
On it. If I console log the item, I can see it being "57300", "730" etc etc. Which is fine. But if I try to do this:
var number = parseInt(item, 10);
And console log what number is... its NaN (should it not be 57300, 730, etc without the quotes?). Is some hidden character messing with me causing parseInt to break?
Upvotes: 0
Views: 3233
Reputation: 79830
I think your initial string is like below,
var result = '"57300","730","17300","17330"';
Since you are splitting with ,
as delimiter, you will end up getting like below,
data = ["\"57300\"","\"730\"","\"17300\"","\"17330\""];
Basically a string with quotes.. And when you parse using parseInt
parseInt("\"57300\"", 10); //throws NaN
Solution:
Instead you can wrap that data with []
and instead of split
use parseJSON
function. See below,
var result = '"57300","730","17300","17330"';
result = '[' + result + ']';
var data = $.parseJSON(result);
$.each(data, function (i, item) {
var number = parseInt(item, 10);
alert(number);
});
DEMO: http://jsfiddle.net/mYysX/
Upvotes: 2
Reputation: 2789
According to your post you are splitting the string on comma which means you are leaving the quotes around the numbers. This means you are doing the equivalent of parseInt("\"573007\""). You would need to strip the quotes before calling parseInt.
Upvotes: 2