2017-04-25 89 views

回答

0

我知道我不應該,但我喜歡這個問題:) 你能改善這個嗎?

function showWeeks(year, month) { 

     let firstWeek = moment(new Date(year,month,1)).isoWeek(); 
     let lastWeek = moment(new Date(year,month+1,0)).isoWeek(); 

     let out = [firstWeek]; 
     if (firstWeek === 52 || firstWeek === 53) { 
     firstWeek=0; 
     } 

     for (let i = firstWeek+1; i<= lastWeek; i++) { 
     out.push(i); 
     } 

     return out; 
    } 

    console.log(showWeeks(2017, 0)); // [52, 1, 2, 3, 4, 5] 
    console.log(showWeeks(2021, 0)); // [53, 1, 2, 3, 4] 
    console.log(showWeeks(2017, 11)); // [48, 49, 50, 51, 52] 
    console.log(showWeeks(1986, 9)); // [40, 41, 42, 43, 44] 
0
const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD'); 
const numOfDays = firstDayOfMonth.daysInMonth(); 
let weeks = new Set(); 

for(let i = 0; i < numOfDays; i++){ 
    const currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD').add(i, 'days'); 

    weeks.add(currentDay.isoWeek()); 
} 

return Array.from(weeks) 
+0

更有效: – surewhatever

0

所以更有效地:

const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD'); 
let weekIndices = []; 

let currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD'); 
weekIndices.push(currentDay.isoWeek()); 

while(currentDay.month() === firstDayOfMonth.month()) { 
    currentDay.add(1, 'weeks'); 
    weekIndices.push(currentDay.isoWeek()); 
} 

return weekIndices; 
相關問題