Leading zero(前導零),也就是常在編號或月份日期前方看到的一串補
0(詳細定義可參閱維基百科:Leading zero)。在前端開發中,實作 JS 數字前補 0 最常應用於訂單流水號對齊(如000123)與時間顯示(如09:05);若您的需求相反,是要在數字或小數點後方補零,則可參考 JavaScript 數字後面補 0(Trailing Zero)。
一、 核心複製即用範本與前導零處理對照
直觀的數字前補 0(以目標總長度 9 位數為例)對比如下:
| 一般數字 | 經過 Leading Zero 前補 0 處理(9 位數) | 常見應用場景 |
|---|---|---|
123 | 000000123 | 會員編號、商品序號對齊 |
44444 | 000044444 | 固定長度金融電文欄位 |
5566666 | 005566666 | 資料庫流水號顯示 |
7890 | 000007890 | 發票或憑證號碼格式統整 |
9876543 | 009876543 | 條碼與憑證字軌補齊 |
二、 3 種 JS 數字前面補 0 實作方法
1. 使用 ES2017 String.prototype.padStart()(現代標準寫法)
在現代瀏覽器與 Node.js 環境中,最簡潔的做法是先用 String() 將數字轉為字串,再呼叫 padStart(目標長度, '0')。當字串長度不足目標長度時,會自動在左側開頭補滿 '0':
/**
* 將數字或字串左側前補 0 至指定長度
* @param {number|string} code - 原始輸入資料
* @param {number} targetLength - 補 0 後的目標總長度
* @returns {string} 補零後的字串
*/
function padLeadingZero(code, targetLength) {
return String(code).padStart(targetLength, '0');
}
console.log(padLeadingZero(123, 9)); // 輸出: "000000123"
console.log(padLeadingZero('abc123', 10)); // 輸出: "0000abc123"
// 常見實務場景:日期月份與時分秒補 0(固定 2 位數)
const month = 5;
const day = 9;
console.log(`${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
// 輸出: "05-09"
2. 使用 Array.join('0') 與 slice()(支援超過長度截斷)
若除了在前方補 0 之外,還希望當輸入長度超過 dataLength 時只保留末尾指定位數,可使用 Array.join('0') 搭配負數索引 slice(-dataLength):
// 數字、字串前補 0
// code : 輸入的資料(字串或數字)
// dataLength : 資料補 0 後的長度
function LeadingZero(code, dataLength) {
var str = Array(dataLength + 1).join('0') + code;
return str.slice(0 - dataLength);
}
var str = 'abc123';
console.log(LeadingZero(str, 10));
// 輸出: "0000abc123"
如果希望前面補的不是數字 '0',而是其他自訂代號(例如 '*' 或 '#'),直接把 join('0') 或 padStart(targetLength, '0') 中的 '0' 改成要補的字元即可。
3. 相容早期 IE 老系統寫法
若維護的系統仍需在早期 IE 環境執行,可預先串接固定長度的 '0' 字串,再透過 slice(0 - dataLength) 由右往左截取指定長度:
// input: (123, 8) , output : "00000123"
function LeadingZeroLegacy(code, dataLength) {
var str = '0000000000' + code;
return str.slice(0 - dataLength);
}
var str = 'abc123';
console.log(LeadingZeroLegacy(str, 10));
// 輸出: "0000abc123"
三、 常見問題與排錯 Q&A
Q1:為什麼在程式碼裡直接寫 const num = 00123 會報錯或數值變掉?
- 問題原因:在 JavaScript 中,數字字面量(Numeric Literal)若以
0開頭(如0123),在非嚴格模式下會被當成八進位(Octal)解析(0123會變成十進位的83),而在嚴格模式('use strict')下則會直接拋出SyntaxError。 - 解決思路:前導零只存在於**字串型別(
String)**中,儲存或顯示前導零時請一律使用字串(如"00123")。
Q2:遇到負數(如 -5)呼叫 String(-5).padStart(4, '0') 為什麼會變成 "00-5"?
- 問題原因:
String(-5)轉為字串後是"-5",padStart只負責在整個字串的最左邊補'0',不會自動跳過負號。 - 解決思路:若需處理負數前導零,可先取絕對值
Math.abs(n)補零後,再根據n < 0補回負號:const formatSignedZero = (n, len) => (n < 0 ? '-' : '') + String(Math.abs(n)).padStart(len, '0'); console.log(formatSignedZero(-5, 3)); // 輸出: "-005"
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!