Home > front end >  JS 4 digit array counter
JS 4 digit array counter

Time:11-18

I'm trying to make a 4 digit counter (e.g. 0000, 0001, ... 0152, 0153, ...) in JS and I have created the following logic, however, I have a bug when the numbers reach something like 0099. Is there a better way of doing this?

    c = [0,0,0,0]
    c = c.reverse();

    c[0]  ;

    for (let i = 0; i < c.length-1; i  ) {
        if (c[i] >= 9) {
            if(i > 0 && c[i-1] != 9){
            } else {
                c[i] = 0;
                if (c[i 1] == 9) {
                    c[i 1] = 0;
                    c[i 2]  ;
                } else {
                    c[i 1]  ;
                }
            }
        }
    }

    c = c.reverse().join("");

CodePudding user response:

Why not just count up an int and then convert it to 4-digits with

myInt.toLocaleString("en", {minimumIntegerDigits: 4, useGrouping: false})
  • Related