问题描述:
要求输出的数字长度是固定的,如长度为2,数字为1,则输出01,即不够位数就在以前补足0。
解决方法:
方法1 chrome
- function fn1(num, length) {
- return (num/Math.pow(10,length)).toFixed(length).substr(2);
- }
方法2 spa
- function fn2(num, length) {
- return ( "0000000000000000" + num ).substr( -length );
- }
方法3 ip
- function fn3(num, length) {
- return (Array(length).join('0') + num).slice(-length);
- }
上述三种方法的效率以下: string
- console.time('time1');
- fn1();
- console.timeEnd('time1');
- console.time('time2');
- fn2();
- console.timeEnd('time2');
- console.time('3');
- fn3();
- console.timeEnd('time3');