Leading zero 前導零,也就是常在數字前面看到的一串補0,有興趣可以看維基百科的詳細解釋。
直觀的對比就如下:
一般數字 | 經過 Leading Zero 處理 |
---|---|
123 | 000000123 |
44444 | 000044444 |
5566666 | 005566666 |
7890 | 000007890 |
9876543 | 009876543 |
JS 數字前面補0
程式在處理資料時,很多時候都會用到Leading zero的概念,尤其一串編號要進行格式統整時,這時可以直接照下面這樣做。
// 數字、字串前補0
// code : 你輸入的資料(字串、數字)
// dataLength : 資料補0後的長度
function LeadingZero( code, dataLength){
var str = Array(10).join('0') + code;
return str.slice(0 - dataLength)
}
var str = 'abc123'
console.log(LeadingZero(str , 10))
// output : '0000abc123'
如果你希望前面補的不是數字0 ,而是其他自訂的代號,可以直接把 join()中的0改成你要補的代號就好。
相容 IE 老系統
如果你用的系統很老,還在使用 IE 開啟,較早期的版本是沒有支援Join的,所以可以改寫成以下代碼:
// input: (123 , 8) , output : 00000123
function LeadingZero( code, dataLength){
var str = '0000000000' + code;
return str.slice(0 - dataLength);
}
var str = 'abc123'
console.log(LeadingZero(str , 10))
// output : '0000abc123'
Creare un cont Binance
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
binance রেজিস্টার করুন
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Registrati
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
binance clone script
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
binance cpm
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
как вывести usd с binance на карту
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
米糕
Where is the doubt?
gate io верификация
Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.
米糕
Where is the doubt?
lazio fan token
Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!