【发布时间】:2016-09-30 08:14:02
【问题描述】:
我有两个日期数组。第一个包含所有预订日期,第二个包含用户将选择的“开始日”和“结束日”之间的日期。
现在我必须确认从完全预订的日期数组中找不到开始和停止之间的天数。
我正在使用 Vue.js 来更新数据。
这是我为获取这些日期所做的工作:
/**
* Get dates from datepicker and format it to the same format that fully booked array has it's dates.
**/
var day1 = moment( this.startDate, 'DD/MM/Y').format('Y,M,D');
var day2 = moment( this.endDate, 'DD/MM/Y').format('Y,M,D');
var start = new Date(day1);
var end = new Date(day2);
/**
* Get dates between start and stop and return them in the dateArray.
**/
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(start, end);
/**
* Set dateArray in to Vue.js data.
**/
this.$set('daysBetweenStartStop', dateArray);
/**
* Get arrays of dates from the Vue.js data. calendar = Booked dates | matchingDays = Dates between start and stop.
**/
var calendar = this.fullDates;
var matchingDays = this.daysBetweenStartStop;
/**
* @description determine if an array contains one or more items from another array.
* @param {array} haystack the array to search.
* @param {array} arr the array providing items to check for in the haystack.
* @return {boolean} true|false if haystack contains at least one item from arr.
*/
var findIfMatch = function (haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
};
var matching = findIfMatch(calendar, matchingDays);
/**
* Check the results. If false we are good to go.
**/
if (matching){
alert('WE FOUND A MATCH');
} else {
alert('GOOD TO GO');
}
数组的格式如下:
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
我的问题是,即使这两个数组具有完全相同的日期,它们仍然会以某种方式被视为不相同。任何想法如何让它工作?
【问题讨论】:
-
数组总是排序的吗?
-
您的意思是您需要查看两个数组之间的差异还是需要查看数组中的匹配项?
-
@Gal 是的,完全预订的数组来自其他函数,该函数从另一个数组中过滤特定日期,然后将它们设置在完全预订的数组中。匹配天数数组来自开始日和结束日,它将从开始到结束将项目推送到数组。
-
@Deepakrao 必须检查 matchDay 数组中是否有任何日期在日历数组中。所以我需要查看数组中的匹配项。 (如果有匹配的日期 -> 返回 true)
-
一个日期是一个对象,两个日期对象永远不会相等。最好的选择是将日期转换为字符串或数字等。
标签: javascript arrays date vue.js