-2

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:

  1. why do i have to assign subArr[i] to tmp? Using myFunc(subArr[i]) will return that i is undefined?
  2. why in myFunc i only receive the last value of subArr array?

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]();
        }
    });
}
Mark
  • 645
  • 2
  • 9
  • 27

2 Answers2

0

why do i have to assign subArr[i] to tmp?

You don't. That isn't the solution proposed by the duplicate question.

Using myFunc(subArr[i]) will return that i is undefined?

i won't be undefined. It will be the same as subArr.length.

subArr[i] will be undefined, because subArr.length is the number of items in the array and the array is zero indexed.

why in myFunc i only receive the last value of subArr array?

Because that is the last value you copied to tmp before the loop ended.


As the high rated answer on the question you link to says, you need to copy i or subArr[i] to a new scope so it won't change next time you go around the loop.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Would you mind making a practical example over my code? I'm not getting out of it... – Mark Oct 06 '17 at 08:41
0

Simply use let :

for (var i = 0; i < subArr.length; i++) {
    let tmp = subArr[i];
    mainObj.push({
        key: function(varsFromLibrary) {
            myFunc(tmp);
        }
    });
}

Or why cant you simply copy the value into the object?:

for (var i = 0; i < subArr.length; i++) {
    mainObj.push({
        tmp:subArr[i],
        key: function(varsFromLibrary) {
            myFunc(this.tmp);
        }
    });
}

Another try of explaining: Lets imagine youre a byciclist. You want to measure your speed so you ask 10 friends of you to stand next to the route at certain points and to tell you your speed. Some pseudocode:

const friends = [];
var speed = 20;//youre really fast
for(var point = 1; point < 10; point++){
  speed -= 2;//youre slowing down

 friends.push({
   ask(){
     console.log(point, speed);
    }
 });
}

Now afterwards you stand at the last point 10 together with your friends and you ask them for the current speed and the point they stay at. What will they tell you? Exactly, they are all standing next to you at point 10 and your current speed is 0. You asked them for the current speed and not to remember the current speed. If you want them to remember it, they need to write it down:

friends.push({
  speed,//every friend object has the current value stored
  point,
  ask(){ console.log(this.speed,this.point)}
});

Or you need to create 10 parallel universes your friends stay in, so if you ask them for your speed they will still see you driving next to them:

 for(let point = 1; point < 10; point++){
   let localspeed = (speed -= 2);//youre slowing down
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thanks a lot Jonas, very exhaustive! Wish I had just your really helpful reply from the beginning! :) – Mark Oct 06 '17 at 09:31