在JavaScript中,我需要填充。

例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。

一种方法是用这个数减去4得到我需要放0的个数。

有没有更巧妙的方法?


当前回答

为了好玩,我们不用循环来创建额外的0:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}

其他回答

因为你提到了它的长度总是4,我不会做任何错误检查来让这个光滑。;)

function pad(input) {
    var BASE = "0000";
    return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}

想法:简单地替换'0000'与数字提供…问题是,如果输入是0,我需要硬编码它返回'0000'。哈哈

这应该够光滑了。

JSFiddler: http://jsfiddle.net/Up5Cr/

Try:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

现在测试:

var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"

DEMO


在ECMAScript 2017中,我们有了新的方法padStart和padEnd,其语法如下。

“弦”。padStart (targetLength, padString]):

现在我们可以用

const str = "5";
str.padStart(4, "0"); // "0005"

你说过你有个号码

String.prototype.padZero= function(len, c){
    var s= '', c= c || '0', len= (len || 2)-this.length;
    while(s.length<len) s+= c;
    return s+this;
}
Number.prototype.padZero= function(len, c){
    return String(this).padZero(len,c);
}

为了好玩,我们不用循环来创建额外的0:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}
function padToFour(number) {
  if (number<=9999) { number = ("000"+number).slice(-4); }
  return number;
}

是这样的吗?

额外的难以理解但更流畅的单行ES6版本:

let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;

ES6isms:

let is a block-scoped variable (as opposed to var’s functional scoping) => is an arrow function that, among other things, replaces function and is prepended by its parameters If an arrow function takes a single parameter, you can omit the parentheses (hence number =>) If an arrow function body has a single line that starts with return, you can omit the braces and the return keyword and simply use the expression To get the function body down to a single line, I cheated and used a ternary expression