4

How can I pass multiple and unlimited arguments and one or two parameters to a function?

Example:

function myFunction(_id, _class, arg1, arg2, arg3, arg4, etc...){
    console.log($(_id).html());
    console.log($(_class).html());

    for(var i = 0; i < args.length; i++) {
        alert(args[i]);
    }
}

myFunction("#myDiv",".mySpan", "Hello World!", "Bonjour le monde!", "Hola mundo!", "Ciao mondo", "Hallo Welt!", "etc");
Mustapha Aoussar
  • 5,833
  • 15
  • 62
  • 107

2 Answers2

12

You can use the arguments object. It is an Array-like object corresponding to the arguments passed to a function.

function myFunction(_id, _class){
    console.log($(_id).html());
    console.log($(_class).html());

    for(var i = 2; i < arguments.length; i++) {
        alert(arguments[i]);
    }
}

myFunction("#myDiv",".mySpan", "Hello World!", "Bonjour le monde!", "Hola mundo!", "Ciao mondo", "Hallo Welt!", "etc");

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
7

More of a future answer:

ECMAScript 6 introduces a new parameter syntax specifically for that, the "rest" parameter. The rest parameter has to be preceded by three dots (...) and must be the last parameter in the list.

Example:

function myFunction(_id, _class, ...args){
    console.log($(_id).html());
    console.log($(_class).html());

    for(var i = 0; i < args.length; i++) {
        alert(args[i]);
    }
}

DEMO (only FF15+)


So far, only Firefox 15+ supports it.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    This will be useful when all browsers get around to supporting it. This feature will make a lot of code a lot more readable. Thanks for including it as an answer :) – Chris Cirefice Apr 11 '14 at 14:04