Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is it just me, or is programming more than one elevator buggy?

I used a for( var i =0;i < elevators.length;++i) statement to apply my code to each elevator, but people only keep using the last one. Could someone give me a hint? ;)



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.


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: