Ste*_*ano 3 javascript arguments function
我定义了一个可以接受任意数量参数但不需要任何参数的函数:
function MyFunction() { //can take 0, 1, 1000, 10000, n arguments
//function code
}
Run Code Online (Sandbox Code Playgroud)
现在我想编写另一个函数,每次使用可变数量的参数调用MyFunction:
function Caller(n) {
var simple_var = "abc";
MyFunction() //how can i pass simple_var to MyFunction n times?
}
Run Code Online (Sandbox Code Playgroud)
提前致谢 :)
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);
}
Run Code Online (Sandbox Code Playgroud)
值得一提的是,webkit上的参数长度限制为65536.