1

I need to programmatically create a Javascript functions array from an array of strings.

For example if my array is this:

myArray = ['a', 'b', 'c', 'd']

I need to create something like this:

myFunctArray = [
    function(d) {
        return d['a'];
    },
    function(d) {
        return d['b'];
    },
    function(d) {
        return d['c'];
    },
    function(d) {
        return d['d'];
    }
]

Now I need to be able to do this programmatically for any array so I tried this:

for(var i = 0; i < myarray.length; i++){
    myFunctArray.push(function(d){            
        return d[myArray[i]];
    });
}

What I get is an array with functions all identical to the last one. I think there's an issue of scope, but I cannot find a solution. I tried a lot of different variants with no luck and Google didn't help. Any help appreciated, thanks!

moncino07
  • 47
  • 1
  • 13

1 Answers1

1

It is indeed a scope problem related to use i inside a function without "freezeing" the value. You could solve it with this closure

for(var i = 0; i < myarray.length; i++){
    function(index) {
        myFunctArray.push(function(d){            
            return d[myArray[index]];
        });
    }(i); // call immediately inline defined function
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155