There is an array of functions that execute different code. It is necessary to make one function out of these functions, when called, all functions from the array would be executed at once.
const a = ()=>{console.log("1")};
const b = ()=>{console.log("2")};
const arr = [a,b];
const fn = () =>{
arr[0]();
arr[1]();
}
I need to make such a result in code, rather than manually calling functions.
I tried to do this by simply iterating through the array using a for loop, but the question is, is there any way to do this without increasing the index? Should I use it as a recursive function or something else?
Solving the problem using a loop:
const fn = () =>{
for(let i = 0; i < arr.length; i++){
arr[i]();
}
}
Is there some solution that doesn’t use a loop? Maybe nest a function within a function somehow?
3
Answers
You can use the forEach() method like this:
Here’s one I use, to run them asynchronously in a way. This is to avoid hanging the event loop, there is a small
timeout
between the calls.Another way to loop through arrays is to use the array’s built-in forEach() method.Each item of the array is passed to the function one by one.
Also reference: Why is my forEach loop not editing my array?
{The forEach() method does not directly manipulate array indices.}
I hope this helps. Happy coding!