简体   繁体   中英

Padding a number with leading zeros in JavaScript?

I'm trying to figure out the sample answer I've found.
Could anyone explain the code below step by step?
The 'str = "0" + str' part is most confusing.

const fillZero = function (n, w) {
    let str = String(n);
    for (let i = str.length; i < w; i++) {
      str = "0" + str;
    }
    return str;
}

  console.log(fillZero(5, 3)); // 005
  console.log(fillZero(12, 3)); // 012
  console.log(fillZero(123, 3)); // 123

With str = "0" + str he is using string concatenation. For example, if the string was Hello , after that line of code it will be 0Hello .

Usually when using i in the for loop, most people would set i = 0, you are setting it to the length of characters of "n". So as long as n < w (w = 3, according to above), you will be adding 0 + n until n = w.

in the first example: n = 1, w = 3 .

str = 0 + 5 after first iteration THEN str = 0 + 05 after second iteration

i is no longer lesser than 3 , so final output is 005 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM