Push Functions into an Array - Loop through and Splice?

后端 未结 5 1289
南笙
南笙 2021-02-01 10:22

Using Javascript i need to be able to:

1: Push a certain amount of the same function (with a different parameter in each) into an array.

2: Then run each functio

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 10:56

    First of all you are not pushing functions into the array at the moment, you execute the func instead. To achieve the push your func should look like this:

    // Function for array objects - alert passed parameter
    function func(num){
      return function(){
        alert(num);
      }
    }
    

    Now if your functions are synchronous you could simply iterate over the array

    for(var i in arr){
      arr[i]();
    }
    console.log('done');
    

    If we are dealing with asynchronous functions then they need to have a callback:

    // Function for array objects - alert passed parameter
    function func(num){
      return function(callback){
        alert(num);
        callback();
      }
    }
    

    And then you can either use a counter to run in parallel.

    var count = arr.length;
    for(var i in arr){
      arr[i](function(){
        if(--count === 0){
          console.log('Done');
        }
      });
    }
    

    Or in sequence:

    function run(){
      var fn = arr.shift();
      if(!fn){
        console.log('Done');
      } else {
        fn(run);
      }
    }
    run();
    

提交回复
热议问题