問題描述
在 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?
推薦答案
ES2017更新
您可以使用內置的 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模板網!