[英]how to add the 0 to the the array in javascript?
var months = range(1, 12);
我正在嘗試使用上面的代碼片段生成 1 到 12 之間的數字我得到了結果
[ {
label: '1',
value: '1',
},
{
label: '2',
value: '2',
}, ..... {
label: '12',
value: '12',
}, ]
像這樣但我想要 output 像這樣
[ {
label: '01',
value: '01',
},
{
label: '02',
value: '02',
}, ..... {
label: '12',
value: '12',
}, ]
如何像這樣實現 output。
這是我的范圍 function
function range(start, end) {
return Array(end - start + 1)
.fill()
.map((_, idx) => ({
label: start + idx,
value: start + idx,
}));
}
const array = [...Array(13).keys()] // 創建從 0 到 13 的數組 array.shift() // 刪除數組的第一個元素,這對我們來說是 0 不需要的元素 const months = array. map(month => month >= 10? month: '0'+month) // 檢查數組的每個值,如果值大於或等於 10,我們將其加 0
嘗試這個
function range (start, end) {
const arr = [];
for(var i = start; i<=end; i++) {
const value = i.toString().padStart(2, '0');
arr.push({label: value, value});
}
return arr;
}
用法
range(1,12)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.