简体   繁体   中英

Don't Understand why forEach cannot access Array its Looping Over

I have this code which needs to compare start and end times. The start and end times are in an array of objects. I need to drill into the objects to compare the values. Error is occurring on the if statement line. Seems like it cannot access the array that it is looping through. Why? I have added the arg to the loop to allow it to do so.

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))

You should add one more condition in your if statement like:

if (index < (array.length - 1) && element.endTime <= array[index+1].startTime) {

}else if (index == (array.length - 1)){
  // your logic for last record
}

Just assume when forEach loop reached on last index. that time see your if condition

if (element.endTime <= array[index+1].startTime)

When we are trying to get startime (array[index+1].startTime) it's showing error. because because we are trying get startime form undefined. loop already reach on last index and we are trying to get value of (index + 1) which is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM