我正在创建一个可重用的函数,其中包含多个/未知数量的变量和一个回调。
//the number of variable will be dynamic
var a = "this is a.";
var b = "this is b.";
function callback(){
console.log('callback successful');
}
//totalUp() will be reusable function
function totalUp(allVariables, callback){
console.log('Here are the complete list: ' + allVariables + '.');
callback();
}
//how do I pass unknown number of arguments(a and b) into one parameter?
totalUp({a,b},callback);
在上面的代码中,我以对象的形式传递 a 和 b,但这不起作用。
最佳答案
使用 ES6
您可以对其使用参数解构:
function test(callback, ...params) {
console.log(params); // ["a", "b"];
console.log('Here are the complete list: ' + params.join(", ") + '.');
}
test(callback, "a", "b");
没有 ES6
function test(params, callback) {
console.log(params); // ["a", "b"];
console.log('Here are the complete list: ' + params.join(", ") + '.');
}
test(["a", "b"], callback);
关于javascript - 将多个/未知数量的变量传递给 JavaScript 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54625609/