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

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


当前回答

以下提供了一个快速的解决方案:

函数numberPadLeft(num, max, padder = "0"){ 返回"" == (num += "") ?“”: (dif = Max - num.length, dif > 0 ? 微调电容器。重复(dif < 0 ?0: dif) + num: num) }

其他回答

如果性能真的很关键(遍历数百万条记录),则可以预先生成填充字符串数组,从而避免每次调用都这样做。

时间复杂度:O(1)。 空间复杂度:O(1)。

const zeroPads = Array.from({ length: 10 }, (_, v) => '0'.repeat(v)) 函数 zeroPad(num, len) { const numStr = String(num) return (zeroPads[len - numStr.length] + numStr) }

我对这个话题的一点贡献(https://gist.github.com/lucasferreira/a881606894dde5568029):

/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
    for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
    return (+o < 0 ? "-" : "") + n;
};

用法:

fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"

我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)

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'

使用递归:

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

最新的方法要简单得多:

var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})

输出:“02”