Hacker News new | ask | show | jobs
by archgoon 4162 days ago
You're probably hitting an issue with the way that closures work in javascript (and many other languages).

    for(var i = 0; i < elevators.length; ++i) {
        elevator[i].on("floor_button_pressed",
             function(floorNum){ elevator[i].goToFloor(floornum)});
    }
Doesn't do what one might expect. When the anonymous function is invoked, it looks up the value of the 'i' identifier, which will have changed it's value to elevators.length by the end of the loop. To get the behavior you want, I've seen people do

    for(var i = 0; i < elevators.length; ++i) {
        (function(i){
            elevator[i].on("floor_button_pressed",
                function(floorNum){ elevator[i].goToFloor(floornum)});
        })(i);
    }
This creates a new scope, which ensures that 'i' has the value that was passed in. I'm afraid I'm a little too tired to look up the parts of the spec that make the semantics clear.
1 comments

Thank you! Your suggestion makes sense indeed and works fine!
You can also use:

  elevators.forEach(function(elevator, elevatorNumber) {...});
This will provide each elevator with its index in the elevators array.