Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Lua's ellipsis in JavaScript?

In Lua, a function like this would be valid:

function FuncCallHack(Func, ...)
    return Func(...)
end

Is there a way I could do this in JavaScript? ... means "all unindexed parameters in the form of an ungrouped array" to those unfamiliar with Lua. I have tried ... in JavaScript, and it appeared to be nonfunctional, and as Google doesn't like searching for special characters, it's not much help.

like image 500
Weeve Ferrelaine Avatar asked Jan 01 '14 19:01

Weeve Ferrelaine


3 Answers

JavaScript has the arguments pseudo-array and the apply function; you can do that like this:

function FuncCallHack(Func) {
    return Func.apply(this, [].slice.call(arguments, 1));
}

here's how that works:

  1. arguments - This is a pseudo-array containing all of the arguments passed to the function by the calling code (including the format argument Func).

  2. [].slice.call(arguments, 1) is a way to get an array of all of the arguments except the first one. (It's a common idiom. It works by applying the Array#slice method to the arguments pseudo-array, using Function#call [which is a lot like Function#apply below, it just accepts the args to pass on differently].) Sadly, arguments itself doesn't necessarily have a slice method because it's not really an array.

  3. Then we use the Function#apply method (all JavaScript functions have it) to call Func using the same this value that was used for the call to FuncCallHack, and passing on all of the arguments except Func to it.

You could also define it slightly differently:

function FuncCallHack(Func, args) {
    return Func.apply(this, args);
}

...which is still really easy to use:

FuncCallHack(SomeFunction, [1, 2, 3]);
// Note this is an array --^-------^
like image 192
T.J. Crowder Avatar answered Oct 23 '22 16:10

T.J. Crowder


Javascript does not yet support this feature.

Instead, you can loop through the arguments array-like object to see every parameter.

To get an array of all of the parameters after the first two (assuming two named parameters), you can write

Array.prototype.slice.call(arguments, 2)
like image 3
SLaks Avatar answered Oct 23 '22 18:10

SLaks


With ES6 comes native support for this, it's named Rest parameters and Spread operator:

function FuncCallHack(Func, ...args) {
    return Func(...args)
}

Feature availability.

like image 1
user Avatar answered Oct 23 '22 17:10

user