[英]How to convert single digit integer into double digit [Javascript]
我想將1,2,3,..9,10,11,12...24
轉換為01,02,03,...09,10,11,12,...24
。 我嘗試了這些解決方案。 這些都沒有解決我的目的:
我正在處理一個Angular項目,我正在Typescript 中執行此操作。 這是我的代碼:
monthpikcer.component.ts
monthSlice() {
let monthStartingIndex = 0;
monthStartingIndex = ("0" + monthStartingIndex).slice(-2); //error
let monthEndingIndex = 24;
for(monthStartingIndex =0; monthStartingIndex < monthEndingIndex; monthStartingIndex++) {
...
}
}
但是對於行monthStartingIndex = ("0" + monthStartingIndex).slice(-2)
,我收到一個錯誤:
“字符串”類型不能分配給“數字”類型。
我希望它是01, 02, 03...10,11,12,13...24
。 請告訴我如何在不更改變量數據類型的情況下執行此操作,因為稍后我必須對它們進行一些算術運算。
您不能在數字前面添加 0,也不能將其轉換為字符串。
兩者都做:
(5).toString().padStart(2,0); // returns "05"
嘗試這樣的事情:
function convert(n) {
n = String(n)
if (n.length == 1)
n = '0' + n
return n
}
convert(0) // -> "00"
convert(1) // -> "01"
convert(9) // -> "09"
convert(14) // -> "14"
convert(20) // -> "20"
我沒有經常使用 TypeScript,但由於它是強類型的,並且您最初將monthStartingIndex
聲明為一個數字,我認為這會導致錯誤。 您可以嘗試以下方法嗎?
此外,該代碼段實際上沒有意義,因為您要轉換為字符串,然后將其用於迭代。 也許你想在 for 循環中這樣做?
monthSlice() {
let monthStartingIndexValidate = "0";
monthStartingIndexValidate = ("0" + monthStartingIndexValidate).slice(-2); //error
let monthEndingIndex = 24;
for(monthStartingIndex = 0; monthStartingIndex < monthEndingIndex; monthStartingIndex++) {
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.