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);
});
// 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);
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.+foo is a shorthand for parseInt(foo, 10)foo = '10 dollars'; then parseInt() works but + doesn't.parseInt() is a bit more clear/readable than a unary +, in my opinion. Conciseness isn't everything.+foo is a shorthand for new Numbervar 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});
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.