I ask this question again as user Cerbrus have marked the previous question as a duplicate of this question. Can someone be so kind to show me how the question indicated by this user, should solve the code below? I can't find a match between those situations (even thought they are similar).
I need to pass a variable to a function inside a for loop. Here's an example:
var mainObj = [],
    subArr = ['val1', 'val2'],
    tmp;
for (var i = 0; i < subArr.length; i++) {
    tmp = subArr[i];
    mainObj.push({
        key: function(varsFromLibrary) {
            myFunc(tmp);
        }
    });
}
Here I have 2 problems:
- why do i have to assign subArr[i]totmp? UsingmyFunc(subArr[i])will return thatiis undefined?
- why in myFunci only receive the last value ofsubArrarray?
UPDATE
I've updated the code as follows but i get TypeError: funcs[j] is not a function
var mainObj = [],
    subArr = ['val1', 'val2'],
    tmp,
    funcs = [];
function createfunc(i) {
    return function() { console.log("My value: " + i); };
}
for (var i = 0; i < subArr.length; i++) {
    funcs[i] = createfunc(subArr[i]);
}
for (var j = 0; j < subArr.length; j++) {
    tmp = subArr[i];
    mainObj.push({
        key: function(varsFromLibrary) {
            funcs[j]();
        }
    });
}
 
     
    