Home > Blockchain >  How to generate 4 digit Number from 0000 to 9999 using JS
How to generate 4 digit Number from 0000 to 9999 using JS

Time:08-02

I want to print sequential number from 0000 to 9999.

This code just print 0000

var pad = (function(num) {
  return function() {
    var str = String(num  );
    while (str.length < 4) str = "0"   str;
    return str;
  }
})(1);

from here How to generate a four digit code (i.e 0001) javascript

I did some changes but did't work with me:

var j = 0;
for (j; j <= 9999; j  ) {
  var pad = (function(num) {
    return function() {

      var str = String(num  );
      while (str.length < 4)
        str = "0"   str;
      return str;
    }
  })(0);
  console.log('Loop', j);
}
console.log('Number', pad());

CodePudding user response:

One liner using Array.from:

const generatePaddedNums = (n) => Array.from(
  { length: n },
  (_, i) => i.toString().padStart((n - 1).toString().length, '0')
)
console.log(generatePaddedNums(10000))
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

CodePudding user response:

You should put the print pad() inside the loop and the function pad declared only once before the loop

var j = 0;
var pad = (function(num) {
  return function() {
    var str = String(num  );
    while (str.length < 4) str = "0"   str;
    return str;
  }
})(1); 
for (j; j <= 9999; j  ) {
  console.log('Number',pad())
  console.log('Loop', j);
}

CodePudding user response:

you have to call pad() function inside for Loop

Refer below code

var pad = (function(num) {
    return function() {
        var str = String(
            num  );
        while (str.length <
            4)
            str = "0"   str;
        return str;
    }
})(1);

for (var i = 0; i < 9999; i  ) {
    console.log('Number', pad());
}
  • Related