在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?

注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。


当前回答

也许我太天真了,但我认为这在一行简单而有效的代码中就可以实现(对于正数):

padded = (value + Math.pow(10, total_length) + "").slice(1)

只要你保持你的长度根据你的值集(在任何零填充),这应该是可行的。

步骤如下:

10的幂与正确的0数相加[69+1000 = 1069] 转换为字符串+"" [1069 => "1069"] 对第一个1进行切片,这是第一个乘法的结果["1069" => "069"]

对于自然列表(文件,dirs…)是非常有用的。

其他回答

这个方法不是更快,但它相当原生。

zeroPad = function (num, count) {
    return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};

如果填充数事先知道不超过某个值,还有另一种不循环的方法:

var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

function zeroFill(number, width) {
    // make sure it's a string
    var input = number + "";  
    var prefix = "";
    if (input.charAt(0) === '-') {
        prefix = "-";
        input = input.slice(1);
        --width;
    }
    var fillAmt = Math.max(width - input.length, 0);
    return prefix + fillZeroes.slice(0, fillAmt) + input;
}

测试用例在这里:http://jsfiddle.net/jfriend00/N87mZ/

不要白费力气;使用下划线字符串:

js小提琴

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // Yields: '000005'

ECMAScript 2017: 使用padStart或padEnd

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"

更多信息:

https://github.com/tc39/proposal-string-pad-start-end https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

我们的测试是假的,因为我的有个错别字。

zeroPad = function (num, count) {
    return ((num / Math.pow(10, count)) + '').substr(2);
};

Paul的是最快的,但我认为.substr比.slice快,即使它多了一个字符;)