Reputation: 63
Let's say I have an integer score = 345
. How do I store each digit seperatly in an array?
This is what I want:
ScoreValue[0] = 5
ScoreValue[1] = 4
ScoreValue[2] = 3
Or if there's any other way to access each digit seperatly with JS that might work too (I'm a newb at this).
Upvotes: 3
Views: 2734
Reputation: 45
try this. Using a for loop, force the score to a String then store each digit as a Number in ScoreVaue[i]
for(i=0;i<String(score).length;i++){ScoreValue[i] = Number(String(score).charAt(i))}
Upvotes: 0
Reputation: 58581
You can turn your number into a string, and then split it up, before manipulating the resulting array...
var score = 345
ScoreValue = score.toString().split('').reverse()
Upvotes: 1
Reputation: 160883
Try:
ScoreValue = String(score).split(''); // gives you ['3', '4', '5']
ScoreValue = String(score).split('').reverse(); // gives you ['5', '4', '3']
If you want the element still be number, then
// gives you [5, 4, 3]
ScoreValue = String(score).split('').reverse().map(function(e) {return +e;});
Upvotes: 5