千萬里不及你
2022-09-23 09:37:31
場景:我有一些字符串需要將數值遞增 1,而不會丟失字符串中的任何內容。Example strings:"000000" should equal to "000001""000100" should equal to "000101""000009" should equal to "000010"我嘗試了一些東西,從最后開始循環到每個字符,但在某些情況下是錯誤的。我認為可能有更好的方法來做到這一點。
2 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
您可以使用padStart()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
/*
"000000" should equal to "000001"
"000100" should equal to "000101"
"000009" should equal to "000010"
*/
const a = "000000";
const b = "000100";
const c = "000009";
console.log((Number(a)+1).toString().padStart(6,"0"));
console.log((Number(b)+1).toString().padStart(6,"0"));
console.log((Number(c)+1).toString().padStart(6,"0"));
添加回答
舉報
0/150
提交
取消