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

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


当前回答

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"

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

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

只是另一种解决方案,但我觉得更容易辨认。

函数zeroFill(text, size) { 而(文本。长度< size){ Text = "0" + Text; } 返回文本; }

如果你使用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 " > < /脚本>

post,如果这是你正在寻找的,将剩余的时间以毫秒为单位转换为字符串,如00:04:21

function showTimeRemaining(remain){
  minute = 60 * 1000;
  hour = 60 * minute;
  //
  hrs = Math.floor(remain / hour);
  remain -= hrs * hour;
  mins = Math.floor(remain / minute);
  remain -= mins * minute;
  secs = Math.floor(remain / 1000);
  timeRemaining = hrs.toString().padStart(2, '0') + ":" + mins.toString().padStart(2, '0') + ":" + secs.toString().padStart(2, '0');
  return timeRemaining;
}