-1

我将如何使用 javascript 或 jquery 为其添加前导零?

for (im=1;im<=31;im++){
     days[im]=everyDay[im];
}
4

5 回答 5

1

考虑:

for (var t, im=1; im<=31; im++){ 
  t = everyDay[im]; 
  days[im] = (t < 10? 0 : '') + t; 
}
于 2012-04-23T04:17:04.823 回答
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);
}
于 2012-04-23T03:42:08.890 回答
0

在它前面加上一个 0,然后取最后两个字符:

var days = {};
for (im=1;im<=31;im++){
     days[im] = ('0' + im).substr(-2);
}
于 2012-04-23T03:42:51.690 回答
0
for (im=1;im<=31;im++){
  days[im] = (everyDay[im] < 10 ? '0' : '') + everyDay[im];
}
于 2012-04-23T04:01:26.327 回答
0
for (var im=1;im<=31;im++){
     var x = parseInt(everyDay[im]);
     if(x < 10)
     days[im]='0' + x;
     else days[im]= x;
}
于 2012-04-23T04:51:15.210 回答