我如何使用javascript或jquery为此添加前导零?
for (im=1;im<=31;im++){
days[im]=everyDay[im];
}
答案 0 :(得分:1)
考虑:
for (var t, im=1; im<=31; im++){
t = everyDay[im];
days[im] = (t < 10? 0 : '') + t;
}
答案 1 :(得分:0)
如果您希望days
数组中的前导零。您可以使用天数创建另一个数组作为此类字符串,并使用它所属的一个或另一个,或在新数组上使用parseInt()
:
var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
strDays = [];
for (var i = 0, l = days.length; i < l; i++) {
strDays.push(String(days[i]).length < 2 ? '0' + days[i] : String(days[i]));
}
// `strDays` prints: ["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"]
修改强> 更短:
var strDays = [];
for (var i = 1; i < 32; i++) {
strDays.push(('' + i).length < 2 ? '0' + i : '' + i);
}
答案 2 :(得分:0)
前缀为0,然后取最后两个字符:
var days = {};
for (im=1;im<=31;im++){
days[im] = ('0' + im).substr(-2);
}
答案 3 :(得分:0)
for (im=1;im<=31;im++){
days[im] = (everyDay[im] < 10 ? '0' : '') + everyDay[im];
}
答案 4 :(得分:0)
for (var im=1;im<=31;im++){
var x = parseInt(everyDay[im]);
if(x < 10)
days[im]='0' + x;
else days[im]= x;
}