3

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).

3 Answers 3

5

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;});
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

0

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))}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.