BlueEyesWhiteDragon
BlueEyesWhiteDragon

Reputation: 427

Arrays in function parameters?

Is it possible to do the following (or an equivalent):

function a(foo, bar[x]){
    //do stuff here
}

Thanks in advance.

Upvotes: 0

Views: 48

Answers (2)

user949300
user949300

Reputation: 15729

Since JavaScript is not statically typed, you cant insist on an array. You can do something like this: (far from perfect but usually does the job)

function a(foo, bars) {
  if (!Array.isArray(bars))
    bars = [bars];

  // now you are sure bars is an array, use it
}

I find that naming arrays in the plural, e.g. "bars" instead of "bar", helps, YMMV.

Upvotes: 4

bto.rdz
bto.rdz

Reputation: 6720

yes, it is possible, as you have noticed you never especify de type of your variables, you only do var a = 1 so here is the same case, you dont have to tell javascript it is an array, just pass it, it will work

function myFunction(foo, array){

}

and the call

var myFoo = { name: 'Hello' };
var myArray = [ 1, 2 ]
myFunction(myFoo, myArray);

hope it helps

Upvotes: 1

Related Questions