Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS 4 digit array counter

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

myInt.toLocaleString("en", {minimumIntegerDigits: 4, useGrouping: false})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading