javascript - 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 函数。您可以使用 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
推荐阅读
- pug - 我希望有人能帮助我解决我的哈巴狗错误。我的主页正在运行,但联系人显示错误
- jenkins - Jenkins 相同并行阶段的更快语法
- .htaccess - Htaccess 拒绝访问某些 IP 的特定页面
- php - Laravel 购物车销毁方法删除卡片中的所有物品
- reactjs - 我在 react.js 中陷入无限循环。如何解决这个问题?
- mailkit - 我无法使用 mailki 发送两封电子邮件
- javascript - 如何在 javascript 中解决此问题
- css - 在按钮焦点上,为什么我会得到两个不同的边框半径?
- typescript - 密钥名称具有已知前缀但完整密钥未知的打字稿接口
- google-sheets - 在 Google 表格中,如何合并包含部分重复条目的表格以仅返回最相关的信息?