删除数组元素并将它们填充到 javascript 中的另一个数组中

Remove array elements and populate them in another array in javascript

我试图在每次迭代中分隔每个月的日期。我有一个数组 var selected=["pre populated with special dates"],其中包含所有选定的日期。现在在这段代码中,我如何修改它以从 selected[] 数组中删除每个月的日期并在每次迭代中仅使用这个特定月份的日期填充 thisMonthDates[]

   var ind=start.getMonth();
            var thisMonthDates = [];
            while(ind<=yearDifference){    
                for (var k = 0; k < selectedArrayLength; k++) {
                    if (new Date(selected[k]).getMonth() == monthIndex[ind]) {
                        thisMonthDates = selected[k];
                        //console.log(new Date(thisMonthDates[k]));
                    }
                }
                for(var eachDt=0; eachDt<thisMonthDates.length; eachDt++) {
                   //code for highlighting the dates
                }
                ind++;
            }

以下是selected[]数组内容。而thisMonthDates[]是循环前的一个空数组。

selected = [Date 2015-01-06T19:00:00.000Z, 
Date 2015-01-13T19:00:00.000Z,Date 2015-01-20T19:00:00.000Z,Date 2015-01-27T19:00:00.000Z, 
Date 2015-02-03T19:00:00.000Z,Date 2015-02-10T19:00:00.000Z,Date 2015-02-17T19:00:00.000Z, 
Date 2015-02-24T19:00:00.000Z,Date 2015-03-03T19:00:00.000Z,Date 2015-03-10T19:00:00.000Z, 
Date 2015-03-17T19:00:00.000Z,Date 2015-03-24T19:00:00.000Z,Date 2015-03-31T19:00:00.000Z, 
Date 2015-04-07T19:00:00.000Z,Date 2015-04-14T19:00:00.000Z,Date 2015-04-21T19:00:00.000Z, 
Date 2015-04-28T19:00:00.000Z,Date 2015-05-05T19:00:00.000Z,Date 2015-05-12T19:00:00.000Z, 
Date 2015-05-19T19:00:00.000Z];

看看这个例子是否有帮助:

http://plnkr.co/edit/XbnJV0B0bO00o4iJdBtV

var selected = [];
var JANUARY = 0
var FEBRUARY = 1
var MARCH = 2;
selected.push(new Date(2015, FEBRUARY, 15));
selected.push(new Date(2015, JANUARY, 10));
selected.push(new Date(2015, FEBRUARY, 6));
selected.push(new Date(2015, MARCH, 25));

var thisMonth = [];

for (var i = 0; i < selected.length; i++) {
    if (selected[i].getMonth() === FEBRUARY) {
        thisMonth.push(selected[i]);
    }
}

console.log(selected);
console.log(thisMonth);

并且输出:

[Sun Feb 15 2015 00:00:00 GMT+1100 (AEDT), Sat Jan 10 2015 00:00:00 GMT+1100 (AEDT), Fri Feb 06 2015 00:00:00 GMT+1100 (AEDT), Wed Mar 25 2015 00:00:00 GMT+1100 (AEDT)]
[Sun Feb 15 2015 00:00:00 GMT+1100 (AEDT), Fri Feb 06 2015 00:00:00 GMT+1100 (AEDT)]

这个循环应该可以解决问题

for (var k = 0; k < selectedArrayLength; k++) {
    if (new Date(selected[k]).getMonth() == monthIndex[ind]) {
        thisMonthDates.push(selected.splice(k, 1));
        k--; // since we removed an element we need to decrement k
    }
}