简体   繁体   English

将函数推入数组-循环和拼接?

[英]Push Functions into an Array - Loop through and Splice?

Using Javascript i need to be able to: 使用Java语言,我需要能够:

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? 现在,我似乎能够执行任务1,2和4,但是我对如何在运行后从数组中拼接出函数感到困惑-有人可以帮忙吗? 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: 到目前为止,我的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);
}

First of all you are not pushing functions into the array at the moment, you execute the func instead. 首先,您现在不将函数推入数组,而是执行func。 To achieve the push your func should look like this: 要实现推送,您的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();
// 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);
}​

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. 对我来说,从数组中执行每个函数,然后在完成循环后设置“ array = []”会更有意义。 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. 但是,视情况而定,这仍然可能是做您正在做的事情的最佳方法,我只是想我应该考虑一下。

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");

http://jsfiddle.net/nZ459/1/ 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();
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM