4

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.

Jo Colina
  • 1,870
  • 7
  • 28
  • 46
  • you could use a json or an array in the argument. Like that you will be able to pass diffents information – David Laberge Jul 08 '15 at 15:52
  • 1
    You mean you wanted to pass a single array instead of a bunch of arguments? Check [`apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). – Teemu Jul 08 '15 at 15:52

3 Answers3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
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)
Skydda
  • 166
  • 3
-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

waders group
  • 538
  • 3
  • 7