在JavaScript中使用前导零填充数字[重复]

在JavaScript中,需要对数字进行前导零填充,例如数字9变为'0009',数字10变为'0010'。文章讨论了不同方法,包括使用`padStart()`方法,以及ECMAScript 6的简洁写法。同时指出,通过数组初始化和整数操作等方法也可实现,但可能不是最优雅的方式。
摘要由CSDN通过智能技术生成

本文翻译自:Pad a number with leading zeros in JavaScript [duplicate]

Possible Duplicate: 可能重复:
How can I create a Zerofilled value using JavaScript? 如何使用JavaScript创建Zerofilled值?

In JavaScript, I need to have padding. 在JavaScript中,我需要填充。

For example, if I have the number 9, it will be "0009". 例如,如果我有数字9,它将是“0009”。 If I have a number of say 10, it will be "0010". 如果我有多个说10,它将是“0010”。 Notice how it will always contain four digits. 请注意它将如何始终包含四位数。

One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put. 一种方法是减去数字减去4得到我需要放置的0的数量。

Is there was a slicker way of doing this? 有没有更明智的方式这样做?


#1楼

参考:https://stackoom.com/question/gGd1/在JavaScript中使用前导零填充数字-重复


#2楼

Try: 尝试:

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

Now test: 现在测试:

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


In ECMAScript 8 , we have new method padStart and padEnd which has below syntax. ECMAScript 8中 ,我们有新方法padStartpadEnd ,它具有以下语法。

'string'.padStart(targetLength [,padString]): 'string'.padStart(targetLength [,padString]):

So now we can use 所以现在我们可以使用了

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

#3楼

function padToFour(number) {
  if (number<=9999) { number = ("000"+number).slice(-4); }
  return number;
}

Something like that? 那样的东西?

Bonus incomprehensible-but-slicker single-line ES6 version: 奖励难以理解但更光滑的单线ES6版本:

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

ES6isms: ES6isms:

  • let is a block scoped variable (as opposed to var 's functional scoping) let是一个块作用域变量(与var的功能范围相对)
  • => is an arrow function that among other things replaces function and is prepended by its parameters =>是一个箭头函数,除其他外,它取代了function并以其参数为前缀
  • If a arrow function takes a single parameter you can omit the parentheses (hence number => ) 如果箭头函数采用单个参数,则可以省略括号(因此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 如果箭头函数体有一行以return开头,则可以省略大括号和return关键字,只需使用表达式即可
  • To get the function body down to a single line I cheated and used a ternary expression 为了将函数体降低到单行,我作弊并使用了三元表达式

#4楼

Not a lot of "slick" going on so far: 到目前为止,并没有太多的“浮油”:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. 使用数字初始化数组时,它会创建一个length设置为该值的数组,以便该数组显示包含许多undefined元素。 Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; 虽然一些Array实例方法跳过没有值的数组元素,但.join()不会,或者至少不完全; it treats them as if their value is the empty string. 它将它们视为值为空字符串。 Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; 因此,您可以获得每个数组元素之间的零字符(或任何“z”)的副本; that's why there's a + 1 in there. 这就是为什么那里有+ 1

Example usage: 用法示例:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10

#5楼

This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0 . 这不是真正的'光滑',但是对于每个填充0 ,进行整数运算比对字符串连接更快。

function ZeroPadNumber ( nValue )
{
    if ( nValue < 10 )
    {
        return ( '000' + nValue.toString () );
    }
    else if ( nValue < 100 )
    {
        return ( '00' + nValue.toString () );
    }
    else if ( nValue < 1000 )
    {
        return ( '0' + nValue.toString () );
    }
    else
    {
        return ( nValue );
    }
}

This function is also hardcoded to your particular need (4 digit padding), so it's not generic. 此功能也根据您的特殊需要进行了硬编码(4位填充),因此它不是通用的。


#6楼

For fun, instead of using a loop to create the extra zeros: 为了好玩,而不是使用循环来创建额外的零:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值