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

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


当前回答

使用递归:

function padZero(s, n) {
    s = s.toString(); // In case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}

其他回答

仅供参考,更清晰,更可读的语法恕我直言

"use strict";
String.prototype.pad = function( len, c, left ) {
    var s = '',
        c = ( c || ' ' ),
        len = Math.max( len, 0 ) - this.length,
        left = ( left || false );
    while( s.length < len ) { s += c };
    return ( left ? ( s + this ) : ( this + s ) );
}
Number.prototype.pad = function( len, c, left ) {
    return String( this ).pad( len, c, left );
}
Number.prototype.lZpad = function( len ) {
    return this.pad( len, '0', true );
}

这也导致结果的视觉和可读性问题比其他一些解决方案更少,这些解决方案强制'0'作为字符;回答我的问题,我该怎么做,如果我想垫其他字符,或在其他方向(右填充),同时保持容易打字,并清楚地阅读。我敢肯定,这也是DRY的最佳示例,实际的前导零填充函数体的代码最少(因为其他相关函数在很大程度上与这个问题无关)。

该代码可通过github用户的gist进行评论(代码的原始来源) https://gist.github.com/Lewiscowles1986/86ed44f428a376eaa67f

在控制台和脚本测试中注意,数值文字似乎需要括号或变量才能调用方法,因此2.pad(…)将导致错误,而(2).pad(0,'#')不会。这似乎对所有数字都是一样的

在所有现代浏览器中都可以使用

numberStr.padStart(numberLength, "0");

函数 zeroFill(num, numLength) { var numberStr = num.toString(); 返回 numberStr.padStart(numLength, “0”); } var 数 = [0, 1, 12, 123, 1234, 12345]; 数字.forEach( 函数(数字) { var numString = num.toString(); var ppadNum = zeroFill(numString, 5); console.log(填充数字); } );

这里是MDN参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

现代浏览器现在支持padStart,你现在可以简单地做:

string.padStart(maxLength, "0");

例子:

字符串= "14"; maxLength = 5;// maxLength是最大字符串长度,而不是max #填充 Res =字符串。padStart(最大长度,“0”); console.log (res);//打印"00014" 人数= 14; maxLength = 5;// maxLength是最大字符串长度,而不是max #填充 res = number.toString()。padStart(最大长度,“0”); console.log (res);//打印"00014"

我在写一个数字基础转换器时,想到了一个荒谬的单行程序。

//这是被诅咒的 函数p (i, w、z) {z z = | | 0; w = w | | 8; i + = "; var o w = i.length %;还啊?[…数组(言).fill (z),……我]. join():我;} console.log (p (8675309));//默认:pad w/ 0到8位 console.log (p(525600年,10));//输入10个数字 console.log(p(69420, 10, 'X'));// Pad w/ X到10位 console.log (p (8675309, 4));//输入4位数字 console.log (p (12345678));//没必要就别拍

或者,以一种不那么容易暴露我把灵魂出卖给黑Perl的形式:

function pad(input, width, zero) {
    zero = zero || 0; width = width || 8;  // Defaults
    input += '';                           // Convert input to string first

    var overflow = input.length % width    // Do we overflow?
    if (overflow) {                        // Yep!  Let's pad it...
        var needed = width - overflow;     // ...to the next boundary...
        var zeroes = Array(needed);        // ...with an array...
        zeroes = zeroes.fill(zero);        // ...full of our zero character...
        var output = [...zeroes,...input]; // ...and concat those zeroes to input...
        output = output.join('');          // ...and finally stringify.
    } else {
        var output = input;                // We don't overflow; no action needed :)
    }

    return output;                         // Done!
}

这个答案与其他答案不同的一点是,它取数字长度对目标宽度的模,而不是简单的大于检查。如果你想确保结果长度是目标宽度的倍数(例如,你需要输出5或10个字符长),这是很方便的。

我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!

我没有看到任何人指出,当你使用String.prototype.substr()与负数时,它从右边计数。

OP问题的一个线性解决方案,即数字5的6位零表示,是:

console.log((“00000000” + 5).substr(-6));

概括起来,我们会得到:

函数pad(num, len) {return ("00000000" + num).substr(-len)}; console.log(垫(5、6)); console.log(垫(45岁,6)); console.log (pad (345 6)); console.log (pad (2345 6)); console.log (pad (12345 6));