将任意数量的参数传递给javascript中的函数 [英] Passing arbitrary number of parameter to a function in javascript

查看:57
本文介绍了将任意数量的参数传递给javascript中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个像这样的javascript函数...

I would like to write a javascript function that works something like this...

f([["a"]], function(e){alert(e);});
// results in alert("a");

f([["a"], ["b"]], function(e1,e2){alert(e1 + ":" + e2);});
//results in alert("a:b");

f([["a", "b"], ["c"]], function(e1,e2){alert(e1 + ":" + e2);});
//results in alert("a:c");alert("b:c");

我可以想到循环的递归解决方案,但是如何向函数发送未知"数量的变量?

I can think of a recursive solution for the looping, but how do I send a "unknown" number of variables to a function?

推荐答案

如果将所有参数都放入数组中(将其称为 foo ),则可以调用函数 fn ,并使用 apply -function

If you put all your arguments into an array (lets call it foo), you can call a function fn with those arguments by using the apply-function.

fn.apply(null, foo)

第一个参数(在这种情况下为 null )是您想要 this 放在被调用函数内部的任何参数. null 可能对您有用.

The first argument (null in this case) is whatever you want this to be inside of the called function. null will probably work for you.

这篇关于将任意数量的参数传递给javascript中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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