First, you use new Array(number).fill()
, which makes an array of undefined
. So, when you call testArray(2)()
, your element
inside your return function is also undefined
. then you tried to find the index of undefined
, it returns 0. The reason it returns 0 is because your functionsArray
is an array of 7 undefined
in your case, then Array.indexOf
will return the first match, and since functionArray[0]
is undefined
, that's why it always return 0 no matter which function you call within your functionArray
. Make sense?
I made a little change of your code, try this. It should work as you would expect. I didn't use Array.indexOf
or any other array methods just because you only want the index, why not consider using the index instead?
If you insist that you want to use Array.indexOf
to solve your problem, you will have to use a forloop inside createArrayOfFunctions
to create your functionsArray
with different elements(e.g. 0,1,2,3,4...7), because new Array(number).fill()
creates array of undefined
, and even if you do Array(number).fill(number)
, you still just create an array of 7s in your case, so that is exactly the same thing as an array of 7 undefined
in your case. So your method won't work. Since you mentioned no forloop, that's why I provided the method using index as described above.
Also I would recommend you to add some logic or create a separate function to make sure no one can call the testArray
out of bound, for example, if you create 7 array functions, you don't want people to be able to call testArray[8]
. I hope this helps. let me know if you have any confusion.
const createArrayOfFunctions = (number) => {
functionsArray = new Array(number).fill(0);
return functionsArray.map((element, index) => {
return () => {
return index;
};
});
};
const testArray = createArrayOfFunctions(7);
console.log(testArray[2]()); // 2;
console.log(testArray[3]()); // 2;
console.log(testArray[1]()); // 2;