在JavaScript中,我需要填充。

例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。

一种方法是用这个数减去4得到我需要放0的个数。

有没有更巧妙的方法?


当前回答

有趣的是,我最近不得不这么做。

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 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"

不漂亮,但很有效。

ES2017更新

你可以使用内置的String.prototype.padStart()

n = 9;
String(n).padStart(4, '0'); // '0009'

n = 10;
String(n).padStart(4, '0'); // '0010'

到目前为止,还没有太多“圆滑”的事情发生:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

当您用一个数字初始化一个数组时,它会创建一个长度设置为该值的数组,以便数组看起来包含许多未定义的元素。虽然一些Array实例方法跳过不带值的数组元素,但.join()不会,或者至少不会完全跳过;它将它们的值视为空字符串。因此,在每个数组元素之间,你得到了一个0字符(或无论“z”是什么)的副本;这就是为什么这里有+ 1。

使用示例:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10
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

因为你提到了它的长度总是4,我不会做任何错误检查来让这个光滑。;)

function pad(input) {
    var BASE = "0000";
    return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}

想法:简单地替换'0000'与数字提供…问题是,如果输入是0,我需要硬编码它返回'0000'。哈哈

这应该够光滑了。

JSFiddler: http://jsfiddle.net/Up5Cr/

这并不是真正的“圆滑”,但它做整数运算比做字符串连接每个填充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位填充)进行了硬编码,所以它不是通用的。