[英]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.