1

I want to define an array of function so I tried the following code, but it does not has the intended result, because the i in the loop cannot be retrieved else where.

<script>
var f = []
for (var i=0; i<1000; i++){
    f[i] = function(){
        return i
    }
}
console.log(f[3]);
</script>

There is the brute-force method to write 1000 lines of codes to define function, is there other ways? In fact I met this problem in Java, Array of function pointers in Java , so answers in both Java or JS would be helpful.

Community
  • 1
  • 1
golopot
  • 10,726
  • 6
  • 37
  • 51

2 Answers2

2

Use an immediately executed function inside the loop to create a scope, so that you can have one variable for each function instance:

var f = []
for (var i=0; i<1000; i++){
  (function(i){
    f[i] = function(){
      return i;
    }
  })(i);
}
console.log(f[3]());

demo: http://jsfiddle.net/Guffa/rPKss/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

It's a closure / scope issue, you have to lock in the value of i

<script>
var f = [];
for (var i=0; i<1000; i++){
    (function(j) {
        f[j] = function(){
            return j;
        }
    })(i); // passing as argument to IIFE makes it local to that scope
}
console.log(f[3]);
</script>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
adeneo
  • 312,895
  • 29
  • 395
  • 388