2


I have a problem, I don't know why if I call tab[4]() or any other number <0,9> the result in the console is always 10. I was guessing the result for i would be i

var tab = [];
for (var i = 0; i < 10; i++) {
    tab[i] = function(){
        console.log(i)
    }
}
Kasia
  • 141
  • 2
  • 5
  • 1
    It is `i`. `i` is `10` when you run the function. You have a for loop that increments it every time you go around the loop until it gets to 10 and the loop stops. – Quentin Mar 01 '17 at 13:21
  • Read http://stackoverflow.com/questions/38944850/for-variable-within-getjson-displayed-wrong/38944865#38944865 – Akshay Khandelwal Mar 01 '17 at 13:22
  • A good explanation to this can be found here: https://medium.freecodecamp.com/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb#c5f5. The easiest solution is to replace `var i = 0` with `let i = 0`. – str Mar 01 '17 at 13:24

2 Answers2

1

Try following

var tab = [];
for (var i = 0; i < 10; i++) {
  tab[i] = (function(i) {
    return function() {
      console.log(i)
    }
  })(i);
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

var tab = [];
for (var i = 0; i < 10; i++) {
  let a = i;
  tab[i] = function(){
      console.log(a);
  }
}
  
tab[1]();
tab[2]();
piotrbienias
  • 7,201
  • 1
  • 28
  • 33