2
    var calls = [];

    for (var y = 1; y <= 10; y++) {
      for (var x = 1; x <= 10; x++) {

        calls.push(function() {
          yooMe(x, y);
        });

      }
    }

    for (var i in calls) {
      calls[i]();
    }

    var yooMe = function(x, y) {
      console.log(x + ':' + y);
    }

I would like to push some functions (x, y as parameters) into array with loop. After than I will loop the array in order to call the function. However, the result is not what I am expexting. The result is 10:10 10:10 ... 10:10. What I expect is 1:1 2:1 3:1 ... 10:10. I think the problem is varaiable referencing problem, but I have no idea how to due with this issue. P.S. Sorry for my poor english

Eric Tang
  • 207
  • 1
  • 4
  • 10

2 Answers2

8

It's because you reference the x and y that change in for loop so when you execute the function you have the last value, to fix this you need to add closure:

for (var y = 1; y <= 10; y++) {
  for (var x = 1; x <= 10; x++) {
    (function(x, y) {
      calls.push(function() {
        yooMe(x, y);
      });
    })(x, y);
  }
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
-1

var calls = [];

for (var y = 1; y <= 10; y++) {
    for (var x = 1; x <= 10; x++) {
        calls.push(yooMe(x, y));
    }
}

for (var i in calls) {
    calls[i]();
}

function yooMe(x, y) {
    return function () {
        console.log(x + ':' + y);
    }
}
Vigneswaran Marimuthu
  • 2,452
  • 13
  • 16