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

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


当前回答

这就是ES6的解决方案。

函数pad(num, len) { 返回“0”。repeat(len - num. tostring ().length) + num; } 警报(垫(1234 6));

其他回答

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 zPad(s,n){
    return (new Array(n+1).join('0')+s).substr(-Math.max(n,s.toString().length));
}

Use:

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

这可以处理负数和数字比字段宽度长的情况。和浮点。

我真的不知道为什么,但没有人用最明显的方式去做。这是我的实现。

功能:

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

原型:

Number.prototype.zeroPad=function(digits){
    var num=this+"";
    while(num.length < digits){
        num='0'+num;
    }
    return(num);
};

很简单,我看不出还有什么比这更简单的了。出于某种原因,我在这里已经看到很多次了,人们只是试图不惜一切代价避免“For”和“while”循环。使用regex可能会为这样一个微不足道的8位数填充花费更多的周期。

这是我写的一个angular提供程序,它利用了@profitehlolz的答案,但使用了内存,这样常用的pad长度-pad字符组合就不会不必要地调用数组构建连接:

angular.module('stringUtilities', [])
    .service('stringFunctions', [function() {
        this.padMemo={ };
        this.padLeft=function(inputString,padSize,padCharacter) {

            var memoKey=padSize+""+padCharacter;

            if(!this.padMemo[memoKey]) {

                this.padMemo[memoKey]= new Array(1 + padSize).join(padCharacter);
            }

           var pad=this.padMemo[memoKey];
           return (pad + inputString).slice(-pad.length);
       };
}]);