用JavaScript中的前导零填充数字 [英] Pad a number with leading zeros in 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> lengthundefined
元素。虽然一些数组实例方法跳过没有值的数组元素,但是.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 manyundefined
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屋!