I defined a function that can take any number of arguments but none is required:
我定义了一个可以接受任意数量参数但不需要任何参数的函数:
function MyFunction() { //can take 0, 1, 1000, 10000, n arguments
//function code
}
Now i would like to write another function that call MyFunction with a variable number of arguments each time:
现在我想编写另一个函数,每次使用可变数量的参数调用MyFunction:
function Caller(n) {
var simple_var = "abc";
MyFunction() //how can i pass simple_var to MyFunction n times?
}
Thanks in advance :)
提前致谢 :)
2 个解决方案
#1
8
Function.apply
can be used to pass an array of arguments to a function as if each element in the array had been passed as an individual argument:
Function.apply可用于将一个参数数组传递给一个函数,就好像数组中的每个元素都已作为单独的参数传递一样:
function Caller(n) {
var simple_var = "abc";
// create an array with "n" copies of the var
var args = [];
for (var i = 0; i < n; ++i) {
args.push(simple_var);
}
// use Function.apply to send that array to "MyFunction"
MyFunction.apply(this, args);
}
Worth to say, argument length is limited to 65536 on webkit.
值得一提的是,webkit上的参数长度限制为65536。
#2
-3
You can use eval (I know, eval is evil).
你可以使用eval(我知道,eval是邪恶的)。
In for loop construct string:
在for循环构造字符串中:
var myCall = "Myfunction(abc, abc, abc)";
and then pass it to eval
然后将其传递给eval
function Caller(n) {
var simple_var = "abc";
eval(myCall);
}
#1
8
Function.apply
can be used to pass an array of arguments to a function as if each element in the array had been passed as an individual argument:
Function.apply可用于将一个参数数组传递给一个函数,就好像数组中的每个元素都已作为单独的参数传递一样:
function Caller(n) {
var simple_var = "abc";
// create an array with "n" copies of the var
var args = [];
for (var i = 0; i < n; ++i) {
args.push(simple_var);
}
// use Function.apply to send that array to "MyFunction"
MyFunction.apply(this, args);
}
Worth to say, argument length is limited to 65536 on webkit.
值得一提的是,webkit上的参数长度限制为65536。
#2
-3
You can use eval (I know, eval is evil).
你可以使用eval(我知道,eval是邪恶的)。
In for loop construct string:
在for循环构造字符串中:
var myCall = "Myfunction(abc, abc, abc)";
and then pass it to eval
然后将其传递给eval
function Caller(n) {
var simple_var = "abc";
eval(myCall);
}