Skip to content Skip to sidebar Skip to footer

How To Check The Index Of A Function In An Array Of Functions In Javascript

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:

Solution 1:

You've encountered a scoping issue.

Here is a solution:

functioncreateArrayOfFunctions(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:

functioncreateArrayOfFunctions(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.

Post a Comment for "How To Check The Index Of A Function In An Array Of Functions In Javascript"