I am trying to convert an array of strings into an array of integers in jquery.
Here is my attempt:
var cdata = data.values.split(",");
$.each( cdata, function(i, l){
l = parseInt(l);
});
asked Aug 22, 2011 at 0:30
user559142
12.6k52 gold badges121 silver badges180 bronze badges
3 Answers 3
I think that you not need use Jquery for this case. In javascript pure:
var str = "1,2,3";
var ArrayOfInts = str.split(',').map(Number); //Output: [1,2,3]
Sign up to request clarification or add additional context in comments.
Comments
// Use jQuery
$('.usesJQuery');
// Do what you want to acomplish with a plain old Javascript loop
var cdata = data.values.split(",");
for(var i = 0; i < cdata.length; i++)
cdata[i] = parseInt(cdata[i], 10);
answered Aug 22, 2011 at 0:36
Paul
142k28 gold badges285 silver badges272 bronze badges
12 Comments
RobG
Or just:
cdata[i] = +cdata[i];. But the excercise seems rathter pointless since strings can be converted to numbers in the expression that needs them as numbers.Pablo Fernandez
+foo is a shorthand for parseInt(foo, 10)Paul
Not really, if
foo = '10 dollars'; then parseInt() works but + doesn't.aroth
Also
parseInt() is a bit more clear/readable than a unary +, in my opinion. Conciseness isn't everything.The Mask
+foo is a shorthand for new Number |
var cdata = data.values.split(",");
$.map( cdata, function(i, l){
return +l;
});
Without jQuery (using the browsers native map method):
"1,2,3,4,5,6".split(',').map(function(e) {return +e});
answered Aug 22, 2011 at 0:31
Pablo Fernandez
106k60 gold badges196 silver badges234 bronze badges
2 Comments
RobG
Array.prototype.map is not widely supported, it should be feature tested first and an alternative provided if not available.
Pablo Fernandez
There's no point in adding the for solution, @PaulPRO covered it really good. I'm leaving this for the sake of completion only (since it's not mentioned elsewhere)
default
parseInt()radix, but I'd also suggest thatparseInt()is the wrong choice except where you specifically want to deal with non-base-10 numbers or where you want to ignore non-digit characters at the end of the source string. Pablo's answer incorporates just one of the better options.