在 JavaScript 中,我需要有填充.
In JavaScript, I need to have padding.
例如,如果我有数字 9,它将是0009".如果我有一个数字,比如 10,它将是0010".注意它总是包含四位数字.
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.
执行此操作的一种方法是将数字减去 4 以获得我需要输入的 0 的数量.
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?
您可以使用内置的 String.prototype.padStart()
n = 9;
String(n).padStart(4, '0'); // '0009'
n = 10;
String(n).padStart(4, '0'); // '0010'
没有很多花哨"的东西.目前为止:
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;
}
当您使用数字初始化数组时,它会创建一个数组,并将 length
设置为该值,以便该数组看起来包含那么多 undefined
元素.尽管一些 Array 实例方法会跳过没有值的数组元素,但 .join()
不会,或者至少不完全;它将它们视为它们的值是空字符串.因此,您会在每个数组元素之间获得零字符(或任何z")的副本;这就是为什么里面有一个+ 1
.
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.
示例用法:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
这篇关于在 JavaScript 中用前导零填充数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!