-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!

1
  • Can you please clearly say what will be the input and what wil be the expected output? Commented May 17, 2017 at 5:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please explain what you changed and why? That will help the OP and readers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.