生成日曆數組(套路)

生成日曆數組,有3個要素。
1.本月共有多少天;
2.上個月一共有多少天(即上個月最後一天是幾號);
3.本月第一天是星期幾
使用Date(),參數分別是this.year(之前定義的年),this.month(之前定義的月)
在向數組中插入數據時,因爲需要判定本月和上月或下月,便於設置類等,所以插入數組中的時對象,包含日期和類名判斷等。
方法如下

  • 定義一個空數組
var arr = [];
  • 本月共有多少天。(Date()函數中,第二個參數是月,但是從0開始計數。第三個參數是天,爲0時會自動向前減一月)
var thisMonthLength = new Date(this.year, this.month, 0).getDate();
  • 上個月共有多少天
var prevMonthLength = new Date(this.year, this.month - 1, 0).getDate();
  • 本月第一天是星期幾
var firstDay = new Date(this.year, this.month - 1).getDay();
  • 本月第一天是星期幾,就讓上月總天數減幾次,添加至數組頭部中
while(firstDay--){
    arr.unshift({
        day: prevMonthLength--,
        current: false
    })
}
  • 本月共有多少天就要向數組中插入多少數據。日期從1開始,定義一個變量,讓變量加加
var count = 1;
while(thisMonthLength--){
    arr.push({
        day: count++,
        current: true
    })
}
  • 有的月份有5周(35天)的數據,有的月份有6周(42天)的數據,需要判定本月天數+上月剩餘天數是否超過35天,如果超過證明數組需要42條數據。下個月的日期依然從1開始
count = 1;
while(arr.length != 35 && arr.length !=42){
    arr.push({
        day: count++,
        current: false
    })
}

生成日曆數組的基本邏輯就是如此
完整代碼如下:

//定義一個calendar函數,返回值是日曆數組
calendar(){
    //定義數組
    var arr = [];
    //本月天數
    var thisMonthLength = new Date(this.year, this.month, 0).getDate();
    //上月天數
    var prevMonthLength = new Date(this.year, this.month - 1, 0).getDate();
    //本月第一天星期幾
    var firstDay = new Date(this.year, this.month - 1).getDay();
    //插入上月剩餘天數
    while (firstDay--) {
        arr.unshift({
            day: prevMonthLength--,
            current: false
        })
    };
    //定義本月日期計數,並插入本月天數
    var count = 1;
    while(thisMonthLength--){
        arr.push({
            day: count++,
            current: true
        })
    };
    //判斷本月日曆數組共有多少天,並補齊下月出現的天數
    count = 1;
    while(arr.length != 35 && arr.length != 42){
        arr.push({
            day: count++,
            current: false
        })
    };
    //返回數組
    return arr;
}

在數組中每個數據需要其他屬性的時候,只需要在插入的數據對象中加入其他屬性。

發佈了38 篇原創文章 · 獲贊 24 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章