by lloydatkinson · 5y ago · 0 comments
for(elevator of elevators) {
elevator.on('idle', () => {
//do some logic with elevator
})
}
It only seems to run for the second elevator rather than both of them? for(var i = 0; i < elevators.length; i++) {
elevators[i].on("idle", function() {
for(var j = 0; j < floors.length; j++) {
elevators[i].goToFloor(j);
}
})
}
it only works for "i < 1" and then only the second elevator moves... its kinda sad as i immediately enjoyed playing ...The reason is that 'let' gives 'i' 'block scope', meaning that each iteration of the loop block gets its own scope so that 'i' isn't overwritten each time, and each function you declare captures the value of 'i' at the time it was declared.
In other words - the way you originally expected 'var' to behave is how 'let' behaves!
The other thread is the same answer but for a slightly different case