There are several different ways to pass an "arbitrary" number of arguments to a function. Perhaps the most useful for your case is the arguments object. Within each function, there is an object similar to an array that contains all the arguments passed to the function.
function shout(msg) { for (var i = 0; i < arguments.length; i++) console.log(arguments[i]); } shout("This", "is", "JavaScript!");
Despite the fact that it seems that the function takes only one argument, you can connect as many as you want, and the function will cycle through all of them. Thus, converting this to your code:
function sum(a) { var total = 0; for (var i = 0; i < arguments.length; i++) total = total + arguments[i]; return total; } sum(1, 2);
Two things to note:
- Since you are accessing the arguments object, you really don't need βanyβ argument list in the function definition (that is, you don't need
a in sum(a) ), but it is usually considered a good idea to give some idea of ββwhat the function expects. . - The arguments object is similar to an array, but is NOT a true array; do not try to use array functions on it, such as push or pop, unless you want to get confused about things.
Regarding the specific syntax sum(1)(2) , however - if it is very specific what you need - I'm at a dead end. Theoretically, to have such a chain, you would need your function to return an object, which is both a function and a number ... that violates the basic rules of JavaScript. I do not think that this is possible without any extremely smart (and probably extremely dangerous) editing of built-in objects, which, as a rule, is frowned upon if there is no good reason for this.
source share