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.
halfer
20.2k20 gold badges111 silver badges208 bronze badges
asked Apr 12, 2014 at 12:17
user2571510
11.4k40 gold badges95 silver badges143 bronze badges
2 Answers 2
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
Sign up to request clarification or add additional context in comments.
4 Comments
user2571510
Thanks very much - this looks great. Can you explain what the ", 10" does ?
Anoop
@user2571510 you can get complete doc for parseInt from developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
user2571510
I see - thanks again ! I will accept as soon as I can.
Amit Joki
@user2571510, check out my answer too
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.
answered Apr 12, 2014 at 12:25
Amit Joki
59.4k7 gold badges80 silver badges97 bronze badges
12 Comments
Amit Joki
@user2571510, this
myVar = 3,5,1,0,7,5 is not valid.user2571510
I checked on this but it doesnt seem to work for me: myArr is empty in this case.
Amit Joki
It works for me. Just copy paste my answer in your browser console and you'll see the result
user2571510
Do I have to declare myArr as an array before ?
Amit Joki
No. You don't have to do anything except copying my answer as it is.
|
lang-js