locked
Javascript loop issue RRS feed

  • Question

  • User665472878 posted
    var funcs = [];
    for (var i = 0; i < 3; i++) {      // let's create 3 functions
      funcs[i] = function() {          // and store them in funcs
        console.log("My value: " + i); // each should log its value.
      };
    }
    for (var j = 0; j < 3; j++) {
      funcs[j]();                      // and now let's run each one to see
    }


    It outputs this:

    My value: 3
    My value: 3
    My value: 3

    Whereas I'd like it to output:

    My value: 0
    My value: 1
    My value: 2

    Friday, May 11, 2018 6:27 PM

Answers

  • User-1134632663 posted

    Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

    What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

    <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

    var funcs = [];
    
    function createfunc(i) {
        return function() { console.log("My value: " + i); };
    }
    
    for (var i = 0; i < 3; i++) {
        funcs[i] = createfunc(i);
    }
    
    for (var j = 0; j < 3; j++) {
        funcs[j]();                        // and now let's run each one to see
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 11, 2018 6:28 PM