How can I pass a varying number of parameters to a

2019-09-02 09:09发布

问题:

I'm aware that you can use a plain Javascript object to accept a varying number of parameters, like so:

function f(params) {
  // do something with params.param1
  // do something with params.param2
  // etc...
}

function t() {
  f({param1: "a", param2: 22, param3: [1,2,3]});  // 3 parameters
  f({param1: 'st'});  // 1 parameter
}

But how can you write a function that calls another function and passes an acceptable number of parameters without knowing in advance how many parameters that function accepts?

For example,

// func is a function object, params is a container of some kind that holds the parameters that that function would accept
function pass_to_func(func, params) {
  func(params);  // func can be anything, which means it can accept any number of params, depending on context
}

I tried this:

function pass_to_func(func, params) {
  func(params.join());  // params is an array of parameters, but this doesn't work 
}

Any suggestion is appreciated, but please keep in mind that it has to be supported in Google Apps Script, since that's the environment I'm dealing with.

回答1:

You can try:

// if params is an array
function pass_to_func(func, params) {
  func.apply(null, params);
}

// if params is not an array
function pass_to_func(func, params) {
  func.call(null, params);
}


回答2:

Pass an object to the function.

function myFunction(obj){
  console.log(obj.color);
}

    var myobj = {
        color:'brown',
        smells:'bad'

    };

myfuntion(myObj);