I’m trying to modify some existing JavaScript code which used apply() to pass an array to a member function normally expecting any number of parameters:
oldFoo: function( arg /* , ..., argN */ ) {
...
}
var ary = ...
oldFoo.apply($, ary)
... other stuff using ary ...
The new code still takes any number of parameters and I still have them as an array to pass in, but I also need to pass in a new parameter before the array
newFoo: function( someObject, arg /* , ..., argN */ ) {
...
}
var ary = ...
newFoo.apply($, ???, ary)
... other stuff using ary ...
So I know I can make a new version of ary with array methods which modify it in-place such as pop/push/shift/unshift but I want to do various things with my array so don’t want to modify it in place.
I know I can build a new temporary array by prepending someObject to it, but that seems to take several lines of code each time.
Is there a more expressive way to achieve what I want to do in about the same number of lines? Something I’m missing about apply or about array functions which return a new array rather than modifying one in-place? I’m already using jQuery so if it has something useful that vanilla JavaScript doesn’t have then that’s great too.
I would do:
That way you won’t modify any existing array of arguments. From MDN: