0

I am trying to create an array containing functions. The tricky part (at least for me) is to create those functions out of an array.

Explanation of a problem

var foo = ["1", 2, 3, 4, "5"];

And now, i need to create a function which will create functions returning those values:

bar[0](); //1
bar[3](); //4

My code so far

function create_functions_array(array) {
    var functions_array = new Array;
    for(var i=0; i<array.length; i++)
       functions_array[i] = function() {console.log(array[i])};
    return functions_array;
}

The thing is, if I put any value inside console.log (inside my function) like:
functions_array[i] = function() {console.log('aaa')};
it will log "aaa" in the console. But when i try to use array variable passed to function, it logs "undefined".

The way I am trying to call this function is var bar = create_functions_array(foo);

Could you please explain me what am I doing wrong?

Kedor
  • 1,488
  • 5
  • 29
  • 53

1 Answers1

2
function create_functions_array(array) {
    var functions_array = new Array;

  for(var i=0; i<array.length; i++) {
       functions_array[i] = function (i) {
         return function() {
           return array[i];
         };
       }(i)
    }

    return functions_array;
}

Demo: http://jsbin.com/hevete/1/edit?js,console

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
  • 1
    @Kedor first function is self-executing function, (i) needs to call it, this function return function that you can use when do bar[0](). About self-executing functions http://goo.gl/feF8cz, and also about closure http://goo.gl/zdpkU1 – Oleksandr T. Dec 21 '14 at 15:23