![](/img/trans.png)
[英]How to improve this function in Javascript which will accept any number of argument?
[英]Javascript - passing callback function as argument that would accept any number of accounts
我问这个问题,意识到我很可能会被禁止重复,但是我却没有能够:
我有一个函数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/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.