我如何将不同数量的参数传递给函数,而不是接受不同数量的参数? [英] How can I pass a varying number of parameters to a function, as opposed to accepting a varying number of paramters?

查看:106
本文介绍了我如何将不同数量的参数传递给函数,而不是接受不同数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我知道你可以使用一个简单的Javascript对象来接受不同数量的参数,函数f(params){
//用params.param1做一些事
//用params.param2做一些事
//等等...
}

函数t(){
f({param1:a,param2:22,param3:[1,2,3]}); // 3个参数
f({param1:'st'}); // 1参数
}

但是如何编写一个调用另一个函数的函数,传递一个可接受的参数数量,而无需事先知道函数接受了多少个参数?

例如,

  // func是一个函数对象,params是某种类型的容器,它保存该函数接受的参数
函数pass_to_func(func,params){
func (PARAMS); // func可以是任何东西,这意味着它可以接受任何数量的参数,具体取决于上下文
}



$ p
$ b

 函数pass_to_func(func,params){
func(params.join( )); // params是一个参数数组,但这不起作用
}

任何建议表示感谢,但请记住,它必须在 Google Apps脚本,因为那是我正在处理的环境。

解决方案

您可以尝试:

 函数pass_to_func(func,params){
func.apply(null,params);
}

//如果params不是数组
函数pass_to_func(func,params){
func.call(null,params);
}


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.

解决方案

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);
}

这篇关于我如何将不同数量的参数传递给函数,而不是接受不同数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆