SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jan 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript - Push Functions into an Array - Loop through and Splice?

    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 function one by one (for this example just an alert of the parameter/number)

    3: After each function i need to be able to SPLICE that function out of the array

    4: Check the Array Length after everytime - Once the array is empty again - alert the user it is complete

    Now i seem to be able to do task 1,2 and 4 but i am sturggling with how to splice out the function from the array after it has run - can anyone help? As i cannot remove the function i am never getting the 'done' alert once all functions have been called

    My javascript code so far is:

    Code:
    // Create empty array
    var array = [];
    
    // Push functions into array - dynamic amount and could be any amount of functions
    array.push(func(1));
    array.push(func(2));
    array.push(func(3));
    
    // Call array manager function after pushing array
    arrayManager();
    
    // Array manager function to splice and detect when finished
    function arrayManager() {
        if (array.length < 1) {
            alert("done");
        }
        else {
        //////////////////////////////////
        // << THIS IS WHERE I DON'T KNOW HOW TO SPLICE THE ITEM FROM THE ARRAY
        //////////////////////////////////
        }
    }
    
    // Function for array objects - alert passed parameter
    function func(num){
        alert(num);
    }

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Don't cross-post.
    Code:
    <script type="text/javascript">
    
    function func( n ){ alert( n ); }
    
    var array = 
    [ function(){ func(1) }, function(){ func(2) }, function(){ func(3) } ];
    
    Array.prototype.callOnce = function( endMsg )
    {
      while( this.length )
        this.splice(0, 1)[ 0 ](); 
       
      alert( endMsg );  
    }
    
    array.callOnce( "Done" );
    
    </script>
    Tab-indentation is a crime against humanity.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •