我有这段代码需要比较开始时间和结束时间。开始时间和结束时间位于对象数组中。我需要深入研究对象来比较值。 if 语句行发生错误。似乎它无法访问它正在循环的数组。为什么?我已将 arg 添加到循环中以允许它执行此操作。
const schedule = [{ startTime: 540, endTime: 600}, {startTime: 550, endTime: 615}, {startTime: 645, endTime: 715}]
// >>> [{startTime: 615, endTime: 645}, {startTime: 715, endTime: 720}]
function findFreeTime(times) {
const freeTime = []
const bookings = times
const timeSlot = {
startTime: 0,
endTime: 0
}
bookings.forEach(function (element, index, array) {
if (element.endTime <= array[index+1].startTime) {
const newSlot = Object.create(timeSlot)
newSlot.startTime = element.endTime
freeTime.push(newSlot)
console.log(freeTime)
}
});
return freeTime
}
console.log(findFreeTime(schedule))
最佳答案
您应该在 if 语句中再添加一个条件,例如:
if (index < (array.length - 1) && element.endTime <= array[index+1].startTime) {
}else if (index == (array.length - 1)){
// your logic for last record
}
关于javascript - 不明白为什么 forEach 无法访问其循环的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431546/