简体   繁体   English

JavaScript - For 循环在一个月对象中添加天数 - moment.js

[英]JavaScript - For Loop to add days in a month object - moment.js

I'm trying to assign every day in the month to my object but I'm only get the last day of each month.我试图将一个月中的每一天分配给我的对象,但我只能得到每个月的最后一天。 How should I do to get full month assigned?我该怎么做才能得到整月的分配?

function loopRange (startDate, range) {
   let fromDate = moment(startDate)
   let toDate = moment(startDate).add(range, 'month')
   let dates = {}

   for (let m = moment(fromDate); m.diff(toDate, 'days') <= 0; m.add(1, 'days')) {
        dates['month_' + m.format('MM')] = {
           'date': m.format('YYYY-MM-DD')
        }
    }

    return dates
}

Result I want:我想要的结果:

dates = {month_11: ['2018-11-01', '2018-11-02', ...]}

You get only the last day because your for-loop advance in day interval.您只能获得最后一天,因为您的 for 循环以天为间隔推进。

However, when assign to dic of dates you put the month as the key - so each iteration (within the same month) override the previous key with the new day -> so you get only yhe lasy day of the months...但是,当分配给dates dic 时,您将月份作为键 - 因此每次迭代(在同一个月内)都会用新的一天覆盖前一个键 -> 这样你就只能得到月份中的那一天...

If you want to have all dates in the time-range as array elements divide on month keys you can use the following code:如果要将时间范围内的所有日期作为数组元素除以月份键,则可以使用以下代码:

for (let m = moment(fromDate); m.diff(toDate, 'days') <= 0; m.add(1, 'days')) 
{
    let month_key = 'month_' + m.format('MM'); 
    if (!dates.hasOwnProperty(month_key))
        dates[month_key] = []; 
    dates[month_key].push(m.format('YYYY-MM-DD'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM