2017-04-25 73 views
1

https://jsfiddle.net/x991kcus/生成與屬性對象的數組中循環

我能夠生成日期數組給定的開始日期和結束日期參數,可以但我想實際上是對象的數組這樣

[{date:"2017-4-01"},{{date:"2017-4-02"}}] 

下面的代碼給了我數組。

function generateDates(startDate, stopDate) { 
    var dateArray = []; 
    var currentDate = moment(startDate); 
    var stopDate = moment(stopDate); 
    while (currentDate <= stopDate) { 
    dateArray.push(moment(currentDate).format('YYYY-MM-DD')) 
    currentDate = moment(currentDate).add(1, 'days'); 
    } 

    return dateArray; 
} 
+0

之前'push'ing到數組中,創建一個對象'O'並分配日期'O操作。 date'。然後將'o'推入陣列。 – Abhitalks

+0

更改dateArray.push({date:moment(currentDate).format('YYYY-MM-DD')})像這樣https://jsfiddle.net/x991kcus/2/ –

+0

你應該使用'date.isAfter(date2 )'而不是'<=' – Rajesh

回答

2

您可以用生成的日期推送一個對象。

dateArray.push({ date: moment(currentDate).format('YYYY-MM-DD') }); 
//    ^^^^^^^          ^wrap in object 

const start_date_of_month = moment().format("YYYY-MM-01"), 
 
     end_date_of_month = moment().format("YYYY-MM-") + moment().daysInMonth(); 
 

 
function generateDates(startDate, stopDate) { 
 
    var dateArray = [], 
 
     currentDate = moment(startDate), 
 
     stopDate = moment(stopDate); 
 

 
    while (currentDate <= stopDate) { 
 
     dateArray.push({ date: moment(currentDate).format('YYYY-MM-DD') }); 
 
     currentDate = moment(currentDate).add(1, 'days'); 
 
    } 
 
    return dateArray; 
 
} 
 

 
console.log(generateDates(start_date_of_month, end_date_of_month));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

+0

omg是這麼簡單嗎?! –

1

可以使用推對象到dateArray

function generateDates(startDate, stopDate) { 
    var dateArray = []; 
    var currentDate = moment(startDate); 
    var stopDate = moment(stopDate); 
    while (currentDate <= stopDate) { 
    obj = {}; 
    obj.date = moment(currentDate).format('YYYY-MM-DD')}; 
    dateArray.push(obj) 
    currentDate = moment(currentDate).add(1, 'days'); 
    } 
    return dateArray; 
} 
0

https://jsfiddle.net/x991kcus/4/

while (currentDate <= stopDate) { 
    var dateObject = {}; 
    dateObject.date = moment(currentDate).format('YYYY-MM-DD'); 
    dateArray.push(dateObject); 
    currentDate = moment(currentDate).add(1, 'days'); 
} 
0

解決方案在JavaScript Object構造是創建 「對象類型」 的標準方式

function dateObject(date) { 
    this.date= date; 
} 

function generateDates(startDate, stopDate) { 
    var dateArray = []; 
    var currentDate = moment(startDate); 
    var stopDate = moment(stopDate); 
    while (currentDate <= stopDate) { 
    dateArray.push(new dateObject(moment(currentDate).format('YYYY-MM-DD'))) 
    currentDate = moment(currentDate).add(1, 'days'); 
    } 

    return dateArray; 
} 

Working Fiddle Here