在JavaScript中,我需要填充。
例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。
一种方法是用这个数减去4得到我需要放0的个数。
有没有更巧妙的方法?
在JavaScript中,我需要填充。
例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。
一种方法是用这个数减去4得到我需要放0的个数。
有没有更巧妙的方法?
当前回答
这并不是真正的“圆滑”,但它做整数运算比做字符串连接每个填充0更快。
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
这个函数也根据您的特殊需要(4位填充)进行了硬编码,所以它不是通用的。
其他回答
你说过你有个号码
String.prototype.padZero= function(len, c){
var s= '', c= c || '0', len= (len || 2)-this.length;
while(s.length<len) s+= c;
return s+this;
}
Number.prototype.padZero= function(len, c){
return String(this).padZero(len,c);
}
为了好玩,我们不用循环来创建额外的0:
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}
这并不是真正的“圆滑”,但它做整数运算比做字符串连接每个填充0更快。
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
这个函数也根据您的特殊需要(4位填充)进行了硬编码,所以它不是通用的。
有趣的是,我最近不得不这么做。
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
使用:
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
不漂亮,但很有效。
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
是这样的吗?
额外的难以理解但更流畅的单行ES6版本:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let is a block-scoped variable (as opposed to var’s functional scoping) => is an arrow function that, among other things, replaces function and is prepended by its parameters If an arrow function takes a single parameter, you can omit the parentheses (hence number =>) If an arrow function body has a single line that starts with return, you can omit the braces and the return keyword and simply use the expression To get the function body down to a single line, I cheated and used a ternary expression