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

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


当前回答

这一种不太本土,但可能是最快的…

zeroPad = function (num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};

其他回答

如果你使用Lodash。

Var n = 1; 警报(_。padLeft(n, 2,0));/ / 01 N = 10; 警报(_。padLeft(n, 2,0));/ / 10 < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js " > < /脚本>

ES6让这一点变得相当微不足道:

function pad (num, length, countSign = true) {
  num = num.toString()
  let negative = num.startsWith('-')
  let numLength = negative && !countSign ? num.length - 1 : num.length
  if (numLength >= length) {
    return num
  } else if (negative) {
    return '-' + '0'.repeat(length - numLength) + num.substr(1)
  } else {
    return '0'.repeat(length - numLength) + num
  }
}

pad(42, 4)          === '0042'
pad(12345, 4)       === '12345'
pad(-123, 4)        === '-100'
pad(-123, 4, false) === '-0100'

现代浏览器现在支持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"

如果npm在你的环境中可用,可以使用一些现成的包:www.npmjs.com/browse/keyword/zeropad。

我喜欢零填充。

安装

$ npm install zero-fill

使用

var zeroFill = require('zero-fill')

zeroFill(4, 1)      // '0001' 
zeroFill(4, 1, '#') // '###1' custom padding
zeroFill(4)(1)      // '0001' partials

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

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