Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass unlimited arguments and one or two parameters to a JavaScript function? [duplicate]

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");
like image 957
Mustapha Aoussar Avatar asked Dec 01 '22 19:12

Mustapha Aoussar


1 Answers

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

like image 183
Arun P Johny Avatar answered Dec 10 '22 12:12

Arun P Johny