在JavaScript中将'1'转换为'0001'

在JavaScript中将'1'转换为'0001'

如何在JavaScript中将转换'1'转换为'0001'而不使用任何第三方库。我使用spritf在php中完成了这个:$time = sprintf('%04.0f',$time_arr[$i]);



暮色呼如
浏览 2439回答 3
3回答

牛魔王的故事

这是一个聪明的小技巧(我认为我以前见过这个):var str = "" + 1var pad = "0000"var ans = pad.substring(0, pad.length - str.length) + str如果substring的第二个参数是负数,那么JavaScript比某些语言更宽容,因此它会“正确地溢出”(或者根据它的查看方式不正确):也就是说,有了以上内容:1 - >“0001”12345 - >“12345”支持负数留作练习;-)快乐的编码。

四季花海

只是为了演示javascript的灵活性:你可以使用onelinerfunction padLeft(nr, n, str){&nbsp; &nbsp; return Array(n-String(nr).length+1).join(str||'0')+nr;}//or as a Number prototype method:Number.prototype.padLeft = function (n,str){&nbsp; &nbsp; return Array(n-String(this).length+1).join(str||'0')+this;}//examplesconsole.log(padLeft(23,5));&nbsp; &nbsp; &nbsp; &nbsp;//=> '00023'console.log((23).padLeft(5));&nbsp; &nbsp; &nbsp;//=> '00023'console.log((23).padLeft(5,' ')); //=> '&nbsp; &nbsp;23'console.log(padLeft(23,5,'>>'));&nbsp; //=> '>>>>>>23'如果你想将它用于负数:Number.prototype.padLeft = function (n,str) {&nbsp; &nbsp; return (this < 0 ? '-' : '') +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Array(n-String(Math.abs(this)).length+1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.join(str||'0') +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(Math.abs(this));}console.log((-23).padLeft(5));&nbsp; &nbsp; &nbsp;//=> '-00023'如果您不想使用,请选择Array:number.prototype.padLeft = function (len,chr) {&nbsp;var self = Math.abs(this)+'';&nbsp;return (this<0 && '-' || '')+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(String(Math.pow( 10, (len || 2)-self.length))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.slice(1).replace(/0/g,chr||'0') + self);}

尚方宝剑之说

String.prototype.padZero=&nbsp;function(len,&nbsp;c){ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;s=&nbsp;this,&nbsp;c=&nbsp;c&nbsp;||&nbsp;'0'; &nbsp;&nbsp;&nbsp;&nbsp;while(s.length<&nbsp;len)&nbsp;s=&nbsp;c+&nbsp;s; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;s;}显示名称,你可以左键填充任何字符,包括空格。我从来没有使用右侧填充,但这很容易。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript