Push Functions into an Array - Loop through and Splice?

后端 未结 5 1291
南笙
南笙 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 11:00

    // Create empty array
    var array = [];
    
    // Push functions into array - dynamic amount and could be any amount of functions
    array.push(function() { func(1); });
    //if you call array.push(func(1)) the function is executed immediatly
    //then null is stored in the array
    array.push(function() { func(2); });
    array.push(function() { func(3); });
    
    // Call array manager function after pushing array
    arrayManager();
    
    // Array manager function to splice and detect when finished
    function arrayManager() {
        while (array.length){
            var fnc=array.splice(0,1)[0]
            fnc();
        }
        alert ("done");            
    }
    
    // Function for array objects - alert passed parameter
    function func(num){
        alert(num);
    }​
    

提交回复
热议问题