查找 JavaScript 中两个日期数组之间的差异

Finding difference between two arrays of Dates in JavaScript

我试图找到两个 Date 数组之间的区别,然后将所有不同的日期分成另一个日期数组以备后用。还有一些我想要它做的功能。有一个变量diffDates。它必须是一个数组,因为它可以容纳一个多月的索引。在 diffDates 的帮助下,我想填充 selectDiffDates

请查看此代码以使其更好并可能更快,以及在这段代码中实现上述最后一个功能的任何想法。谢谢。 Link to fiddle.

Array.prototype.diff = function(a) {
    return this.filter(function(i) {
        return (a.indexOf(i) < 0);
    });
}

var monthIndex = [0,1,2,3,4,5,6,7,8,9,10,11];
var dMarked=[], dFiltered=[], selectDiffDates = [];
dMarked=["Thu Jan 01 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Feb 05 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Mar 05 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Apr 02 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jun 04 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jan 01 2015 00:00:00 GMT+0500 (Pakistan Standard Time)"];

dFiltered=["Thu Jan 08 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Feb 12 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Mar 12 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Apr 09 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu May 07 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jun 11 2015 00:00:00 GMT+0500 (Pakistan Standard Time)"];

var dMarkedMonths = [], dFilteredMonths = [];
for(var i=0; i<dMarked.length; i++){
 dMarkedMonths.push( monthIndex[new Date(dMarked[i]).getMonth()]);   
}
for(var i=0; i<dFiltered.length; i++){
 dFilteredMonths.push( monthIndex[new Date(dFiltered[i]).getMonth()]);   
}

console.log(dMarkedMonths);
console.log(dFilteredMonths);
var diffDates = dFilteredMonths.diff( dMarkedMonths );

console.log("Difference: "+diffDates);

for(var d=0; d<dFiltered.length; d++){
    if(new Date(dFiltered[d]).getMonth() == diffDates){
     selectDiffDates.push(dFiltered[d]);   
    }
}
console.log(selectDiffDates);
$("#console").html(selectDiffDates);

diffDates 是一个数组,因此您不应将数组与单个月份进行比较...而是应该检查 diffDates 数组中是否存在月份:

for(var d=0; d<dFiltered.length; d++){
    if(diffDates.indexOf(new Date(dFiltered[d]).getMonth())>-1){
     selectDiffDates.push(dFiltered[d]);   
    }
}

关于性能部分:请检查更新后的 fiddle http://jsfiddle.net/q7rmr5uq/3/

您目前的逻辑不符合您的要求。目前,您正在选择月份并找到不同的月份,然后根据您获得的月份重新确定日期。但这将跳过所有具有相同月份但不同日期或年份的日期。

满足您要求的更好方法应该包括查找两个日期之间的差异而不是两个月之间的差异。