In the work, if we output the number of the length is fixed, the assumption is 4, if the number is 3, then output 0003, not enough digits in front of the complement of 0, here summed up to provide three different ways to achieve the number of JS code to fill 0 of the operation;
The first: the most original way of writing
function pad (num, n) {
var i = (num + ""). Length;
while (i++ < n) num = "0" + num;
return num;
}
The second: the method of
function Prefixinteger (num, length) {return
(Num/math.pow (10,length)). toFixed (length). substr (2);
}
Third: Methods (more efficient)
function Prefixinteger (num, length) {return
("0000000000000000" + num). substr (-length);
Fourth: Methods (more efficient, concise)
function Prefixinteger (num, length) {return
(Array (length). Join (' 0 ') + num). Slice (-length);
}
Fifth: Method (Magic Recursive method)
/* Magic recursive */
function pad2 (num, n) {
if ((num + ""). Length >= N) return num;
return Pad2 ("0" + num, n);
}
Article reprint
JavaScript Digital 0 Tip: How to make a number in front of a specified length of 0