3 ms·
What am I doing wrong? for(elevator of elevators) { elevator.on('idle', () => { //do some logic with elevator }
by lloydatkinson 5y ago
What am I doing wrong?
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?
- mercora 5y agoi likely ran into the same or a related issue. i dont know much about javascript though. 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 ...
- garaetjjte 5y agoI think this was discussed there: https://news.ycombinator.com/item?id=8933979 https://news.ycombinator.com/item?id=8933979
- mercora 5y agothis did indeed help understanding and fixing the issue.
- davnicwil 5y agoJust in case this is interesting, a potentially more elegant way to solve this with modern JS is to use 'for(let i' instead of 'for(var i'. 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!
- umvi 5y agoShould be `for (let elevator of elevators)`
- lloydatkinson 5y agoOh my god you’re right, oops. I wouldn’t normally make that mistake but no IDE and coding at night apparently isn’t a good mix!
- emiphil 5y agofor (elevator ... Like that is making a new global variable called elevator which is getting overwritten on the next loop. You need to for(const elevator... (or let). The other thread is the same answer but for a slightly different case
- pazqo 5y agoYou should be able to accomplish the same with elevators.forEach((elevator) => {})
- lloydatkinson 5y agoIt could, but favouring FP I'd use for..of for imperative loops where I need to do side-effects, or use .map which is nicer anyway.