Push Functions into an Array - Loop through and Splice?

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

    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.

提交回复
热议问题