根据年月区间获取中间所有的年月列表
<script> let str = '2016-06~2020-03' let thisYear = new Date().getFullYear() function delZero(m) { return m.substring(1) } function addZero(month){ return Number(month) < 10 ? '0' + month : month } function getFullYearMonth(year) { let result = [] for(let i = 1;i<=12;i++){ let item = year + '-' + addZero(i) result.push(item) } return result } function getMonthList(time) { let timeArr = time.split('~'), startYear = timeArr[0].split('-')[0], startMonth = delZero(timeArr[0].split('-')[1]), endYear = timeArr[1].split('-')[0], endMonth = delZero(timeArr[1].split('-')[1]), result = [] if((Number(endYear) - Number(startYear))>1){ let start = Number(startYear) let end = Number(endYear) result.push(...getThisYearLastMonth(startYear,startMonth)) for(let i = start+1;i<end;i++){ result.push(...getFullYearMonth(i)) } result.push(...getThisYearLastMonth(endYear,endMonth)) }else{ timeArr.forEach((item)=>{ let [year,month] = item.split('-') month = delZero(month) result.push(...getThisYearLastMonth(year,month)) }) } return result } function getThisYearLastMonth(year,month){ let arr = [] for(let i = 1;i<=12;i++){ if(year <= thisYear){ if(i>=month){ let item = year + '-' + addZero(i) arr.push(item) } }else{ if(i<=month){ let item = year + '-' + addZero(i) arr.push(item) } } } return arr } let a = getMonthList(str) console.log(a) </script>