-2

I am pretty new level to JavaScript. I have a function taking y as the input to return an array with size y which has almost the same functions as the elements.

This is my code:

  function createArrayOfFunctions(y) {
    var arr = [];
    for(var i = 0; i<y; i++) {
    arr[i] = function(x) {    
      return x + i);}  //Probably this is the issue
    }
    return arr;
  }

  var input = "5,3,2";

  var [y, n, m] = input.split(",");
  console.log("input = " + input);
  [y, n, m] = [parseInt(y), parseInt(n), parseInt(m)]
  var addArray = createArrayOfFunctions(y);
  console.log(addArray[n](m));  //I would like to add up n and m

When I execute the code, the i keeps at 5 instead of iterating from 0,1,2,3,4 for arr[0],arr[1],arr[2],arr[3],arr[4]. As a result, it always output m+y instead of n+m. I have tried to use indexOF and this[i] to figure out the index of the functions, but it does not work. Is there any ways for me to do this?

Thanks!

Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
Michael Lam
  • 415
  • 3
  • 9
  • Can you please clearly say what will be the input and what wil be the expected output? – brk May 17 '17 at 05:08

1 Answers1

1

You've encountered a scoping issue.

Here is a solution:

function createArrayOfFunctions(y) {
  let arr = [];
  for (let i = 0; i < y; i++) {
    arr[i] = function(x) {
      return x + i;
    };
  }
  return arr;
}

The above uses let, which scopes the i variable to each loop iteration.

If you can't use let due to compatibility, use an IIFE for each loop:

function createArrayOfFunctions(y) {
  var arr = [];
  for (var i = 0; i < y; i++) {
    (function() {
        var _i = i;
        arr[_i] = function(x) {
          return x + _i;
        };
    })();
  }
  return arr;
}

The above code caches each i variable for each loop in an IIFE, which keeps it in scope.

wilsonzlin
  • 2,154
  • 1
  • 12
  • 22
  • 2
    Can you please explain what you changed and why? That will help the OP and readers – RaR May 17 '17 at 05:05