有什么方法可以只获取未命名的参数? [英] Is there any way to get only the unnamed arguments?
问题描述
在JavaScript函数中, arguments
是一个类似于数组的对象,包含该函数的所有参数,无论它们是否已命名:
In JavaScript functions, arguments
is an array-like object containing all arguments to the function, whether they are named or not:
function f(foo, bar) {
console.log(arguments);
}
f(1, '2', 'foo'); // [1, "2", "foo"]
有没有办法获取仅未命名的参数,因此您可以执行以下操作?
Is there a way to get only the arguments that are not named, so you could 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"]
但是为什么呢?
一个实际的用例是将Angular模块作为参数注入RequireJS模块:
But why?
A real-world use case is for injecting 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]);
});
由于模块依赖项列表可能变得很大,因此很快变得非常麻烦。虽然我可以将其解决为
As the list of module dependencies can get quite large, this quickly becomes very cumbersome. While I could solve it as
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));
});
这也很麻烦,如果我可以做这样的事情会很好: / p>
this is also rather cumbersome, and it would be nice if I could do something like this instead:
define([
'angular',
'underscore',
'myLibModule', // Exports an Angular module object
'myOtherLibModule', // Exports an Angular module object
], function(angular, _) {
angular.module('MyApp', _.pluck(unnamedArguments, 'name'));
});
当然,在RequireJS中对依赖项进行分组的方法对于此特定用例也足够了。
Of course, a way to group dependencies in RequireJS would suffice just as well for this particular use case.
推荐答案
已声明参数的数量在 length
属性中提供
The number of declared arguments is provided in the length
property of the function.
因此您可以获得参数的索引大于或等于此 length
的参数:
So you can get the arguments whose index is greater or equal to this length
:
var undeclaredArgs = [].slice.call(arguments, arguments.callee.length);
以您不能在严格模式下使用 arguments.callee
从ES5 起,应该尽可能使用对该函数的引用:
As you can't use arguments.callee
in strict mode starting from ES5, you should use a reference to the function whenever possible :
var undeclaredArgs = [].slice.call(arguments, f.length);
这篇关于有什么方法可以只获取未命名的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!