Ich habe 2 Lösungen. Die erste ist die wirklich einfache, um eine Zahl mit Nullen schlecht zu machen, wenn Sie wissen, dass das alles ist, was Sie schnell tun wollen.
Bei der zweiten werden auch negative Zahlen aufgefüllt - genau wie bei der "cleveren" Lösung, die anscheinend die beste Punktzahl hat.
Also los:
// One liner simple mode!
// (always ensure the number is 6 digits long knowing its never negative)
var mynum = 12;
var mynum2 = "0".repeat((n=6-mynum.toString().length)>0?n:0)+mynum;
alert("One liner to pad number to be 6 digits long = Was "+mynum+" Now "+mynum2);
// As a function which will also pad negative numbers
// Yes, i could do a check to only take "-" into account
// if it was passed in as an integer and not a string but
// for this, i haven't.
//
// @s The string or integer to pad
// @l The minumum length of @s
// @c The character to pad with
// @return updated string
function padme(s,l,c){
s = s.toString();
c = c.toString();
m = s.substr(0,1)=="-";
return (m?"-":"")+c.repeat((n=l-(s.length-(m?1:0)))>0?n:0)+s.substr((m?1:0));
}
alert("pad -12 to ensure it is 8 digits long = "+padme(-12,8,0));
alert("pad 'hello' with 'x' to ensure it is 12 digits long = "+padme('hello',12,'x'));