0

Can I pass an array as parameters/arguments in a function?

For example, this works:

key(0, arrowRight, 'regX', anchorLast, 8, 'quartInOut', 175);

This, however, doesn't:

var banana = [0, arrowRight, 'regX', anchorLast, 8, 'quartInOut', 175]
key(banana);

returning Uncaught TypeError: Cannot read property 'x' of undefined from within the key() function. What's undefined here is what should have been arrowRight (an object).

I've tried searching for answers, and most prescribe the use of .apply() (or .call()), but I'm not sure how to apply this to my situation. I'm not even if it's the same problem (still a Javascript beginner).

I didn't post the key() function here, because I don't think it's relevant.

Community
  • 1
  • 1
AKG
  • 2,936
  • 5
  • 27
  • 36
  • What did you try wrt `apply`? – i_am_jorf Jun 27 '13 at 23:26
  • Oh, you added `.apply()` to your question? Or was it there all along? I only remember seeing `.call()` there at first. –  Jun 27 '13 at 23:28
  • @CrazyTrain I mistyped so I added it later :) – AKG Jun 27 '13 at 23:29
  • Oh, alright. Wasn't sure if I just overlooked it. –  Jun 27 '13 at 23:30
  • 1
    Drive-by comment: Just pay attention to the fact that in your first example you're passing in 7 parameters, and in the second you're only passing in 1! **That's** the difference, and that's what `apply` does: takes an array and converts its elements to individual parameters. – ErikE Jun 27 '13 at 23:52

1 Answers1

6

Yes, use .apply() to invoke your key function and distribute an Array or Array-like object as individual arguments to the function.

key.apply(this, banana);

The first argument to .apply() sets the this value of your key function. Here I just used the enclosing this value.

The second argument is the collection of arguments to be passed to your key function.