【问题标题】:Javascript - add more parameters to a callback function [duplicate]Javascript - 向回调函数添加更多参数[重复]
【发布时间】:2011-08-27 03:10:39
【问题描述】:

我正在调用一个需要回调函数作为参数的异步函数。

这里是javascript代码:

for(i in array) 
{
    var item = array[i];
    functionToCall(item[i][1], 50, function(a, b)
    {
        alert(a + b);
    });
}

我无法编辑 functionToCall 函数。我想要做的是像这样在回调函数中使用“item”变量。

for(i in array) 
{
    var item = array[i];
    functionToCall(item[i][1], 50, function(a, b, c)
    {
        alert(a + b + c);
    }, item);
}

但是这段代码不能正常工作。我不能只在函数中使用“项目”,因为它总是使用数组中的最后一项。

那我该怎么做呢?

【问题讨论】:

    标签: javascript callback asynccallback


    【解决方案1】:

    您可以在函数内使用item,但您需要“捕获”它,以免每次都使用数组的最后一个元素。

    for(var i = 0, l = array.length; i < l; ++i) { // better than for .. in
        var item = array[i];
        (function(item, i){
          functionToCall(item[i][1], 50, function(a, b) // do you really re-index item with the same index?
          {
              alert(a + b);
          });
        })(item, i);
    }
    

    【讨论】:

    • 效果比预期好,非常感谢!
    【解决方案2】:

    使用for..in 来迭代数组是个坏主意。改用.forEach(),你的很多问题就迎刃而解了:

    array.forEach(function(item)
    { 
        functionToCall(item[1], 50, function(a, b) 
        { 
            alert(a + b + item[1]); 
        }); 
    }
    

    要在旧浏览器中使用.forEach()see this

    【讨论】:

      【解决方案3】:

      我会尝试这样的:

       function createExecutionCall(itemIndex, number, item)
       {
            return function() { functionToCall(itemIndex, number, function(a, b)
            {
                 // Example, item should be contained within this closure then
                 alert(a + b + item);
            });
       }
      
       for(i in array) 
       {
           var item = array[i];
      
           var call = createExecutionCall(item[i][1], 50, item);
           call();
        }
      

      【讨论】:

        猜你喜欢
        • 2013-12-18
        • 2015-12-27
        • 2015-06-05
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-27
        相关资源
        最近更新 更多