场景:我有一些字符串需要将数值递增 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
提交
取消