Is there a way to get only unnamed arguments?
In JavaScript functions arguments
, an array-like object containing all the arguments to a function, whether they are specified or not: / p>
function f(foo, bar) {
console.log(arguments);
}
f(1, '2', 'foo'); // [1, "2", "foo"]
Is there a way to only get the arguments that are not named so you can do something like this?
function f(foo, bar) {
console.log('foo:', foo, 'bar:', bar, 'the rest:', unnamedArguments);
}
f(1, '2', 'foo'); // foo: 1 bar: "2" the rest: ["foo"]
But why?
In real-world usage, to embed Angular modules as arguments into RequireJS modules:
define([
'angular',
'myLibModule', // Exports an Angular module object
'myOtherLibModule', // Exports an Angular module object
], function(angular, myLibModule, myOtherLibModule) {
angular.module('MyApp', [myLibModule.name, myOtherLibModule.name]);
});
Since the list of module dependencies can get quite large, this quickly becomes very cumbersome. Although I could solve it like
define([
'angular',
'underscore',
'myLibModule', // Exports an Angular module object
'myOtherLibModule', // Exports an Angular module object
], function(angular, _) {
function angularModuleNames(modules) {
return _.pluck(_.pick(modules, function(item) {
return _.has(item, 'name');
}), 'name');
}
angular.module('MyApp', angularModuleNames(arguments));
});
this is pretty cumbersome too, and it would be nice if I could do something like this:
define([
'angular',
'underscore',
'myLibModule', // Exports an Angular module object
'myOtherLibModule', // Exports an Angular module object
], function(angular, _) {
angular.module('MyApp', _.pluck(unnamedArguments, 'name'));
});
Of course, the way the dependencies are grouped in RequireJS will suffice for this particular use case.
source to share
The number of declared arguments is provided in the property of the length
function.
So, you can get arguments whose index is greater than or equal to this length
:
var undeclaredArgs = [].slice.call(arguments, arguments.callee.length);
As you cannot use arguments.callee
in strict mode since ES5 , you should use a function reference whenever possible:
var undeclaredArgs = [].slice.call(arguments, f.length);
source to share