[英]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.