[英]How to get a list of all months from current month to a month in the past using moment.js
[英]How to select current month from a list of months with JavaScript?
我有一個 JSON 格式的月份列表,想從 React Native 的列表中選擇當前月份。
這是我的清單:
Month: [
{ value: "1", label: "JAN", key: "JAN" },
{ value: "2", label: "FEB", key: "FEB" },
{ value: "3", label: "MAR", key: "MAR" },
{ value: "4", label: "APRIL", key: "APRIL" },
{ value: "5", label: "MAY", key: "MAY" },
{ value: "6", label: "JUN", key: "JUN" },
{ value: "7", label: "JUL", key: "JUL" },
{ value: "8", label: "AUG", key: "AUG" },
{ value: "9", label: "SEP", key: "SEP" },
{ value: "10", label: "OCT", key: "OCT" },
{ value: "11", label: "NOV", key: "NOV" },
{ value: "12", label: "DEC", key: "DEC" }
];
通過執行以下操作,您可以將當前月份映射到數組中的月份:
let Month = [ { value: "1", label: "JAN", key: "JAN" }, { value: "2", label: "FEB", key: "FEB" }, { value: "3", label: "MAR", key: "MAR" }, { value: "4", label: "APRIL", key: "APRIL" }, { value: "5", label: "MAY", key: "MAY" }, { value: "6", label: "JUN", key: "JUN" }, { value: "7", label: "JUL", key: "JUL" }, { value: "8", label: "AUG", key: "AUG" }, { value: "9", label: "SEP", key: "SEP" }, { value: "10", label: "OCT", key: "OCT" }, { value: "11", label: "NOV", key: "NOV" }, { value: "12", label: "DEC", key: "DEC" } ]; let currentMonth = Month[new Date().getMonth()]; console.log(currentMonth);
您可以使用查找當前月份索引
const currentMonthIndex = new Date().getMonth() + 1
月份通常從 0 開始所以你必須加 1 然后你可以通過數組過濾
const selectedMonth = months.find(m => m.value === currentMonthIndex)
您可以使用new Date()
javascript 函數,例如:
let month = new Date().getMonth() + 1; //Current Month
它將為您提供當前月份的value
然后您可以將其與您的 JSON 進行比較,例如:
Month.map((item) => {
if(item.value === month){
//Do something
}
})
希望這對你有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.