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.

5
  • What did you try wrt apply? Commented Jun 27, 2013 at 23:26
  • Oh, you added .apply() to your question? Or was it there all along? I only remember seeing .call() there at first. Commented Jun 27, 2013 at 23:28
  • @CrazyTrain I mistyped so I added it later :) Commented Jun 27, 2013 at 23:29
  • Oh, alright. Wasn't sure if I just overlooked it. Commented Jun 27, 2013 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. Commented Jun 27, 2013 at 23:52

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.