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

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


当前回答

我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作

(也适用于负数和小数)

代码:

function fillZeroes(n = 0, m = 1) {
  const p = Math.max(1, m);
  return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}

输出:

console.log(fillZeroes(6, 2))          // >> '06'
console.log(fillZeroes(1.35, 2))       // >> '01.35'
console.log(fillZeroes(-16, 3))        // >> '-016'
console.log(fillZeroes(-1.456, 3))     // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3))  // >> 'Agent 007'

其他回答

我对这个话题的一点贡献(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"

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

function zFill(n,l){
    return 
      (l > n.toString().length) ? 
        ( (Array(l).join('0') + n).slice(-l) ) : 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,'#')不会。这似乎对所有数字都是一样的

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'

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;
}