これに先行ゼロを追加するには、javascriptまたはjqueryをどのように使用しますか?
for (im=1;im<=31;im++){
days[im]=everyDay[im];
}
これに先行ゼロを追加するには、javascriptまたはjqueryをどのように使用しますか?
for (im=1;im<=31;im++){
days[im]=everyDay[im];
}
検討:
for (var t, im=1; im<=31; im++){
t = everyDay[im];
days[im] = (t < 10? 0 : '') + t;
}
配列に先行ゼロが必要な場合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);
}
for (im=1;im<=31;im++){
days[im] = (everyDay[im] < 10 ? '0' : '') + everyDay[im];
}
先頭に 0 を追加し、最後の 2 文字を取得します。
var days = {};
for (im=1;im<=31;im++){
days[im] = ('0' + im).substr(-2);
}
for (var im=1;im<=31;im++){
var x = parseInt(everyDay[im]);
if(x < 10)
days[im]='0' + x;
else days[im]= x;
}