Add 0 to the front of the number from 1 to 9, for example, 0102... 1011..., which is to use JavaScript code to implement zero padding, such as pad () 012. Here we will introduce four javascript methods, and also provide the PHP method.
Add 0 to the front of the number from 1 to 9, for example, 01 02 .... 10 11 ...., javaScript code is used to implement zero padding, such as pad (12, 3) => 012.
Implementation 1:
/* Quiet method */function pad (num, n) {var I = (num + ""). length; while (I ++ <n) num = "0" + num; return num ;}
The above code is too cool to reflect my real level. So there is Implementation 2:
/* Magic recursion method */function pad2 (num, n) {if (num + ""). length> = n) return num; return pad2 ("0" + num, n );}
Magical recursion ~~
However, the trick is a fatal one. The above code uses two lines, which is an insult. Think about it, a line of magic code comes to mind:
/* Tip method */function pad3 (num, n) {return (Array (n). join (0) + num). slice (-n );}
One day, the autumn is refreshing and the heart is relaxed. Sit down in the Bodhi tree with friends and play chess with wine. You said: BP has hurt me since you left. The magic code that you left leaves my hair three years ahead of schedule. I'm surprised: What should I do? My friend looked sad: Do you remember the magical pad3 function? Within one year after you leave, the company's business surge. Pad3 has a bug. in some cases, the first few digits are truncated. For example, pad3 (123456, 5) returns 23456. this bug was discovered by hackers, resulting in several large-scale phishing events and the company's loss of millions. At that time, the boss ordered me to find out the bug in a day, and it took me three days to locate the bug because of your magic code. In addition to pad3, there is also a magic xxoo9 function, at that time ...... Old friends are still nagging. after hearing the first paragraph, I was lost. Looking down at the writing of pad3, there is indeed a bug, which is used in the transaction system, crazy sweat ......
After talking to friends, I couldn't wait to retrieve the pad3 and xxoo9 code from the face's ghost cloud. I was shocked by the test: