方法一、自定义函数实现,不方便自定义调用 function FillZero(p) {return new Array(3 - (p + '').length + 1).join('0') + p;}FillZero(6); //输出006 方法二、String方法一扩展(C#中PadLeft、PadRight) String.proto
方法一、自定义函数实现,不方便自定义调用
function FillZero(p) { return new Array(3 - (p + '').length + 1).join('0') + p; } FillZero(6); //输出006
方法二、String方法一扩展(C#中PadLeft、PadRight)
String.prototype.PadLeft = function (len, charStr) { var s = this + ''; return new Array(len - s.length + 1).join(charStr || '') + s; } String.prototype.PadRight = function (len, charStr) { var s = this + ''; return s + new Array(len - s.length + 1).join(charStr || ''); } var p = 6; p.toString().PadLeft(3, '0'); //输出006 p.toString().PadRight(3, '0'); //输出600
方法三、原理同方法二
<script type="text/javascript"> String.prototype.pad= function (pos,len,padStr) { var padStrs = new Array(len).join(padStr,''); return pos ? (padStrs + this.toString()).substr(0-len):(this.toString() + padStrs).substr(0,len); } String.prototype.lpad = function(len,padStr){ return this.pad(1,len,padStr); } String.prototype.rpad = function(len,padStr){ return this.pad(0,len,padStr); } String.prototype.padLeft = String.prototype.lpad; String.prototype.padRight = String.prototype.rpad; var str="6"; console.log(str.lpad(2,"0")); console.log(str.padLeft(2,"0")); </script>
代码四、
String.prototype.padLeft = function (padChar, width) { var ret = this; while (ret.length < width) { if (ret.length + padChar.length < width) { ret = padChar + ret; } else { ret = padChar.substring(0, width - ret.length) + ret; } } return ret; }; String.prototype.padRight = function (padChar, width) { var ret = this; while (ret.length < width) { if (ret.length + padChar.length < width) { ret += padChar; } else { ret += padChar.substring(0, width - ret.length); } } return ret; };
下面是其他网友的补充
javascript-leftpad方法
原由是微博上出的一则leftpad方法被吐槽的事。
原方法是通过循环挨个拼接字符串的方式,所以效率差了点(会产生N多string对象,导致对象回收慢)
类似
for(i=0;i<cnt;i++){
str=pad+str;
}
改进如下:
//cache var padding1="00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; var padding2=" "; function leftpad(str,length,useSpace){ var padding = padding1; if(useSpace){ padding = padding2; } var cnt = length-str.length; if(cnt<=0) return str; if(cnt<=200) return padding.substring(0,cnt)+str; str=padding+str; return leftpad(str,length,ch); }
思路:
1.减少string对象的生成,所以尽量减少字符串拼接的次数
2.降低时间复杂度
以上就是js中位数不足自动补位扩展padLeft、padRight实现代码的详细内容,更多关于js自动补位 padLeft、padRight的资料请关注易盾网络其它相关文章!