I know the question is hard to understand.
I'm using a drawing library, that requires a "list of points" to draw a polygon. Only, this list is just the arguments of the function. (Passing an array does nothing...)
So, i'm looking for a way to be able to call this function from another one, with a variable number or args. It could be 5, or 6, or 238754, the code will figure it out itself.
Can this be done from an array?
Thank you very much.
答案 0 :(得分:3)
The .apply()
function does exactly what you want: it lets you use an array as a list of arguments.
someFunction.apply(thisRef, someArray)
causes the function to be invoked with someArray[0]
as the first argument, someArray[1]
as the second argument, and so on. The first parameter to .apply()
is the value to use for this
in the call to the function, so what you use there completely depends on what someFunction
would ordinarily expect.
The .apply()
function is on the Function prototype, so it's available via a reference to any function.
答案 1 :(得分:3)
To pass variables to a function from an array you can use Function.prototype.apply
var args = [1,2,3]
function do_stuff(a, b, c) {
...
}
do_stuff.apply(thisValue, args)
答案 2 :(得分:-1)
You can pass any number of parameters to a JS function. But, you have to handle them by iterations in the function definition itself
function myFunc()
{
for(var i=0;i<arguments.length;i++)
console.log(arguments[i]);
}
myFunc(5,3,4,1,8);
Output:
5
3
4
1
8