How do I loop through a numeric function parameter?

Viewed 57

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);
2 Answers

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.

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

Related