在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将支持更大的数字。
其他回答
你说过你有个号码
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);
}
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"
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
因为你提到了它的长度总是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/
你可以这样做:
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将支持更大的数字。