Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

2 of 3
formatting and grammatical improvement(s)

First of all, understand what's wrong with this code:

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
}

Here when the funcs[] array is being initialized, i is being incremented, the funcs array is initialized and the size of func array becomes 3, so i = 3,. Now when the funcs[j]() is called, it is again using the variable i, which has already been incremented to 3.

Now to solve this, we have many options. Below are two of them:

  1. We can initialize i with let or initialize a new variable index with let and make it equal to i. So when the call is being made, index will be used and its scope will end after initialization. And for calling, index will be initialized again:
var funcs = [];
for (var i = 0; i < 3; i++) { 
 let index = i;
 funcs[i] = function() { 
 console.log("My value: " + index); 
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); 
}
  1. Other Option can be to introduce a tempFunc which returns the actual function:
var funcs = [];
function tempFunc(i){
 return function(){
 console.log("My value: " + i);
 };
}
for (var i = 0; i < 3; i++) { 
 funcs[i] = tempFunc(i); 
 
}
for (var j = 0; j < 3; j++) {
 funcs[j](); 
}
Ali Kahoot
  • 3.6k
  • 2
  • 26
  • 28

AltStyle によって変換されたページ (->オリジナル) /