用JavaScript中的前导零填充数字 [英] Pad a number with leading zeros in JavaScript

查看:144
本文介绍了用JavaScript中的前导零填充数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


在JavaScript中,我需要填充。



例如,如果我有数字9,它将是0009。如果我有一些说10,那将是0010。请注意,它总是包含四位数字。



一种方法是将数字减去4以得到我需要放置的0的数量。 p>

是否有这样做的简单方法?

解决方案



 函数pad(n,width,z){
z = z || 0’ ;
n = n +'';
返回n.length> =宽度? n:new Array(width - n.length + 1).join(z)+ n;



$ b当使用数字初始化一个数组时,它会创建一个数组, code> length
设置为该值,以便数组看起来包含许多 undefined 元素。虽然一些数组实例方法跳过没有值的数组元素,但是 .join()不会或者至少不完全是这样。它把它们看作是它们的值是空字符串。因此,你得到每个数组元素之间的零字符(或任何z是)的副本;这就是为什么在那里有一个 + 1



示例用法:

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

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


Possible Duplicate:
How can I create a Zerofilled value using JavaScript?

In JavaScript, I need to have padding.

For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "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.

Is there was a slicker way of doing this?

解决方案

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. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; 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; that's why there's a + 1 in there.

Example usage:

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

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

这篇关于用JavaScript中的前导零填充数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆