Javascript 将函数推入数组 - 循环和拼接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12571744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Push Functions into an Array - Loop through and Splice?
提问by Lauren Reynolds
Using Javascript i need to be able to:
使用 Javascript 我需要能够:
1: Push a certain amount of the same function (with a different parameter in each) into an array.
1:将一定数量的相同函数(每个函数的参数不同)推入数组。
2: Then run each function one by one (for this example just an alert of the parameter/number)
2:然后一个一个运行每个函数(对于这个例子只是一个参数/编号的警报)
3: After each function i need to be able to SPLICE that function out of the array
3:在每个函数之后,我需要能够从数组中拼接该函数
4: Check the Array Length after everytime - Once the array is empty again - alert the user it is complete
4:每次检查数组长度 - 一旦数组再次为空 - 提醒用户它已完成
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
现在我似乎能够完成任务 1,2 和 4,但我正在纠结如何在它运行后从数组中拼接出函数 - 任何人都可以帮忙吗?由于我无法删除该功能,因此一旦调用了所有功能,我就永远不会收到“完成”警报
My javascript code so far is:
到目前为止,我的 javascript 代码是:
// 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);
}
回答by DeadAlready
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:
首先,您目前没有将函数推送到数组中,而是执行 func 。要实现推送,您的 func 应如下所示:
// 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();
回答by Lauren Reynolds
// 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);
}?
回答by prashanth
Is this what you needed?
这是你需要的吗?
1: Push a certain amount of the same function (with a different parameter in each) into an array.
1:将一定数量的相同函数(每个函数的参数不同)推入数组。
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)
2:然后一个一个运行每个函数(对于这个例子只是一个参数/编号的警报)
3: After each function i need to be able to SPLICE that function out of the array
3:在每个函数之后,我需要能够从数组中拼接该函数
4: Check the Array Length after everytime - Once the array is empty again - alert the user it is complete
4:每次检查数组长度 - 一旦数组再次为空 - 提醒用户它已完成
while (k.length > 0) {
k[0].f(k[0].params);
k.shift();
}
alert("done");
回答by Bubbles
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.
“splice”至少有两个参数:第一个是开始删除的索引,第二个是要删除的项目数。当它返回一个新数组时,要获取函数,您需要从拼接中获取第一个值。您还可以在前两个参数后添加任意数量的值;这些将被添加到数组中以代替您已删除的内容。
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.
但是,我很好奇您为什么要这样做 - 虽然我可以将以非常规方式做某事理解为一种智力练习,但如果您不熟悉编程,我会说有更好的方法来做到这一点。当您使用数组中的函数时,没有特别需要从数组中删除项目。对我来说,从数组中执行每个函数会更有意义,然后在完成循环后设置“array = []”。但是,根据情况,这可能仍然是做您正在做的事情的最佳方式,我只是想我会提供一些思考。
回答by Shmiddty
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();
...
}