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!