首页 > 解决方案 > Javascript - 将回调函数作为参数传递,可以接受任意数量的帐户

问题描述

我问这个问题是意识到我很可能会因为重复而被禁止,但我无法:

我有一个函数 A 应该能够接受另一个函数 B 作为它的参数,但是我无法提前知道函数 B 的参数数量的问题:

function A(callback){
    // wish to call the callback function here
}

function B(x){...};
function C(x, y, z){...};

A(B)
A(C(1,2,3))

标签: javascript

解决方案


javascript 中的每个非箭头函数都包含参数对象,它是函数内的局部变量,我们可以将无限数量的参数传递给 javascript 函数。您可以使用 arguments 对象在回调函数中获取回调函数的参数。因此,您不需要知道确切的参数,B 函数是期望的。

function A(callback){
    callback(1,2,3,4............,n arguments)
}

function B(){
   console.log(arguments)
   //iterate over arguments using length property if needed. 
};


A(B)

第二个例子是当我们需要从 A 传递参数和回调函数时。

function A(callback){
    // Array containing all argument of A including callback function
    //Use ES6 Array.from function to convert arguments object to array to use array functions

    let argumentArray = Array.from(arguments);

    // Splice the array from 1 to end to exclude the first argument of A function i.e. callback function B

    let argumentArrayWithoutCallback = argumentArray.slice(1);

    //Pass this array to callback function

    callback(argumentArrayWithoutCallback)
}

function B(){
   console.log(arguments)
   //iterate over arguments using length property if needed. 
};


A(B,1,2,3.......n)

有关参数对象的更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments


推荐阅读