0

I'm having a lot of trouble figuring this one out. I have a function which passes value as a parameter, and I need a way to store each single digit that I'm passing in when I'm calling the function. I'm assuming I need to use a for loop and I can assign each digit to [i] but the logic isn't coming to me.

function assignValue(value) {
  for (let i = 0; i < value.length; i++) {
    // I'M LOST
  }
}
assignValue(123);
4
  • what does this function should return? what kind of structure do you need to store the digits? Commented Sep 22, 2022 at 9:06
  • "I need a way to store each single digit that I'm passing in" - store where, and how? Commented Sep 22, 2022 at 9:08
  • so please provide us the expected the result or more details so that we can help you!!! Commented Sep 22, 2022 at 9:10
  • to loop through something, it needs to be iterable ... a number is not iterable Commented Sep 22, 2022 at 9:11

2 Answers 2

3

There are no "digits" in a value of type number, for the concept of "digits" you have to convert to string in the numbering system you want (for instance, base 10).¹ Once you've converted to string, you can loop through it with code like the code in your question, or more easily with a for-of loop:

function assignValue(value) {
    // Convert to string
    const str = String(value);
    // Loop through the string
    for (const char of str) {
        console.log(char);
    }
}
assignValue(123);


¹ It is possible to do this mathematically, by figuring out what the highest multiple of 10 you need is (100 in your case), and then working through by Math.floor(value / multiple), then doing value %= multiple and multiple /= 10, and continuing that while multiple >= 1:

function assignValue(value) {
    let multiple = 1;
    // Figure out where we need to start -- I'm sure there's a
    // clever mathematics way to do this rather than this brute
    // force approach
    while (multiple < value) {
        multiple *= 10;
    }
    // That took us too far, so:
    multiple /= 10;
    
    // Loop through
    while (multiple >= 1) {
        console.log(Math.floor(value / multiple));
        value %= multiple;
        multiple /= 10;
    }
}
assignValue(123);

But using a string is probably easier.

Sign up to request clarification or add additional context in comments.

Comments

0

Another way to go about it, that's without using the for loop is to turn the number into an array of the digits

function assignValue(value) {
  return Array.from(String(value), Number);
}
console.log(assignValue(123))

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.