根据另一个数组从数组中获取月份范围,JavaScript
假设我们有两个字符串数组。第一个数组包含完全 12 个字符串,每个字符串表示一年里的一个月份,如:-
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
第二个数组包含完全两个字符串,表示一个月份范围,如:-
const monthsRange = ["aug", "oct"];
我们需要编写一个 JavaScript 函数来接收这样的两个数组。然后,该函数应从第一个数组中选出所有位于第二个范围数组指定范围内的月份。
对于上述数组,输出应为:-
const output = ['aug', 'sep'];
请注意,我们在输出中省略了该范围的结束元素 ('oct'),这是该功能的一部分。
示例
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; const range = ['aug', 'dec'];
const getMonthsInRange = (year, range) => {
const start = year.indexOf(range[0]);
const end = year.indexOf(range[1] || range[0]);
// also works if the range is reversed if (start <= end) {
return year.slice(start, end);
}
else {
return year.slice(start).concat(year.slice(0, end));
};
return false;
};
console.log(getMonthsInRange(year, range));输出
控制台中的输出为:-
[ 'aug', 'sep', 'oct', 'nov' ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP