在JavaScript中,我需要填充。
例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。
一种方法是用这个数减去4得到我需要放0的个数。
有没有更巧妙的方法?
在JavaScript中,我需要填充。
例如,如果我有数字9,它将是“0009”。如果我有一个数字,比如10,它将是“0010”。注意它总是包含四位数字。
一种方法是用这个数减去4得到我需要放0的个数。
有没有更巧妙的方法?
当前回答
你可以这样做:
function pad ( num, size ) {
return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}
编辑:这只是一个函数的基本思想,但是为了增加对更大数字(以及无效输入)的支持,这可能会更好:
function pad ( num, size ) {
if (num.toString().length >= size) return num;
return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}
这有两件事:
如果该数字大于指定的大小,它将简单地返回该数字。 使用Math.floor(num)代替~~num将支持更大的数字。
其他回答
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
你可以这样做:
function pad ( num, size ) {
return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}
编辑:这只是一个函数的基本思想,但是为了增加对更大数字(以及无效输入)的支持,这可能会更好:
function pad ( num, size ) {
if (num.toString().length >= size) return num;
return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}
这有两件事:
如果该数字大于指定的大小,它将简单地返回该数字。 使用Math.floor(num)代替~~num将支持更大的数字。
有趣的是,我最近不得不这么做。
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
使用:
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
不漂亮,但很有效。
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"
为了好玩,我们不用循环来创建额外的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;
}