2017-04-25 64 views

答えて

0

私はすべきではありませんが、私はこの質問が好きです:) あなたはこれをimprooveできますか?だから、より効率的に

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; 
関連する問題