Push Functions into an Array - Loop through and Splice?

后端 未结 5 1298
南笙
南笙 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:18

    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();
        ...
    }
    

提交回复
热议问题