最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Incrementing numbers starting from 0000 - Stack Overflow

programmeradmin0浏览0评论

I have a starting number to work from which is 0000 and increment it by one, i have that done, but the result is 1,2,3 instead of 0001,0002,0003 etc. How can I achieve this?

Thank you

I have a starting number to work from which is 0000 and increment it by one, i have that done, but the result is 1,2,3 instead of 0001,0002,0003 etc. How can I achieve this?

Thank you

Share Improve this question asked Mar 22, 2012 at 11:15 gkiddgkidd 1994 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Let n be the number. Then use the String.slice method as follows:

var output = [], n, padded;
for (n=0; n<=9999; n++) {
    padded = ('000'+n).slice(-4); // Prefix three zeros, and get the last 4 chars
    output.push(padded);
}
console.log(output); // ["0000", "0001", ..., "9999"]

Demo: http://jsfiddle/qJSBg/

for (let i = 0; i <= 9; i++) {
      for (let j = 0; j <= 9; j++) {
         for (let k = 0; k <= 9; k++) {
          for (let l = 0; l <= 9; l++) {

           let yournumber = i.toString() + j.toString() + k.toString() + l.toString();
            console.log(yournumber);

          }
       }
   }
}
发布评论

评论列表(0)

  1. 暂无评论