Push Functions into an Array - Loop through and Sp

2019-03-11 12:38发布

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:

// 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);
}

5条回答
Rolldiameter
2楼-- · 2019-03-11 12:52
// 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);
}​
查看更多
Lonely孤独者°
3楼-- · 2019-03-11 12:56

This should do what you're looking for:

var next_func = array.splice(0, 1)[0]

"splice" takes at least two parameters: the first is the index to start removing from, and the second is the number of items to delete. As it returns a new array, to just get the function you get the first value from the splice. You can also add as many values as you'd like after these first two parameters; these will be added to the array in place of what you've deleted.

However, I am curious as to why you are doing it this way - while I can understand doing something in an unconventional manner as an intellectual exercise, if you're new to programming I'd say there's a better way to do this. There's no particular need to delete items from the array as you use functions from it. To me, it would make more sense to execute each function from the array, then set "array = []" after completing the loop. However, depending on circumstance this may still be the best way to do what you're doing, I just figured I'd give some food for thought.

查看更多
何必那么认真
4楼-- · 2019-03-11 13:02

Is this what you needed?

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

function func(num){
    alert(num);
}

var k = [];
k.push({f:func, params:[1]});
k.push({f:func, params:[2]});
k.push({f:func, params:[3]});

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

while (k.length > 0) {
 k[0].f(k[0].params);
 k.shift();
}
alert("done");
查看更多
看我几分像从前
5楼-- · 2019-03-11 13:08

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();
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-11 13:13

http://jsfiddle.net/nZ459/1/

If you want to push each function with its parameters in the manner you're doing, you'll have to wrap the function like so:

function wrapper(arg){
    return function(){
        console.log(arg);
    };
}


var ar = [];

console.log("pushing functions");

ar.push(wrapper(1));
ar.push(wrapper(2));
ar.push(wrapper('three'));

console.log("done pushing functions");

while (ar.length){
    var fn = ar.shift();
    console.log("calling ", fn);
    fn();
}

Alternatively, you could make a generic wrapper that takes a function, and arguments as parameters, and returns an anonymous function.

To answer your question more directly, the simplest way to run through an array in the manner you desire is like this:

while (array.length){
    var item = array.shift();
    ...
}
查看更多
登录 后发表回答