gpt4 book ai didi

javascript - 不明白为什么 forEach 无法访问其循环的数组

转载 作者:行者123 更新时间:2023-12-02 22:45:09 25 4
gpt4 key购买 nike

我有这段代码需要比较开始时间和结束时间。开始时间和结束时间位于对象数组中。我需要深入研究对象来比较值。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com