Reputation: 11377
I have a dynamically filled variable containing numbers formatted as text that are separated by commas.
When alerting this out for testing I get something like: var myVar = 3,5,1,0,7,5
How can I convert this variable into a valid JavaScript or jQuery array containing integers ?
I tried $.makeArray(myVar)
but that doesn't work.
Upvotes: 1
Views: 130
Reputation: 59232
You can just do this:
var myVar = "3,5,1,0,7,5";
var myArr = myVar.split(',').map(function(x){return +x});
myArr
will have integer array.
I changed myVar = 3,5,1,0,7,5
to myVar = "3,5,1,0,7,5"
because the former wasn't valid.
I presume that it is a string.
Upvotes: 1
Reputation: 23208
Simple, try this.
var myVar = 3,5,1,0,7,5;
myVarArray = myVar.split(",");
// Convert into integers
for(var i=0, len = myVarArray.len; I < len; I++){
myVarArray[i] = parseInt(myVarArray[i], 10);
}
// myVarArray is array of integers
Upvotes: 3