Javascript 有没有办法只获取未命名的参数?

Javascript 有没有办法只获取未命名的参数?,javascript,ecmascript-5,Javascript,Ecmascript 5,在JavaScript函数中,是一个类似数组的对象,包含函数的所有参数,无论它们是否命名: function f(foo, bar) { console.log(arguments); } f(1, '2', 'foo'); // [1, "2", "foo"] 有没有办法只获取未命名的参数,这样您就可以这样做 function f(foo, bar) { console.log('foo:', foo, 'bar:', bar, 'the rest:', unnamedArg

在JavaScript函数中,是一个类似数组的对象,包含函数的所有参数,无论它们是否命名:

function f(foo, bar) {
    console.log(arguments);
}
f(1, '2', 'foo'); // [1, "2", "foo"]
有没有办法只获取未命名的参数,这样您就可以这样做

function f(foo, bar) {
    console.log('foo:', foo, 'bar:', bar, 'the rest:', unnamedArguments);
}
f(1, '2', 'foo'); // foo: 1 bar: "2" the rest: ["foo"]
但是为什么呢? 现实世界中的一个用例是将角度模块作为参数注入到RequireJS模块中:

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]);
});
由于模块依赖项的列表可能变得相当大,这很快就会变得非常麻烦。而我可以像你一样解决它

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));
});
这也相当麻烦,如果我能做这样的事情就好了:

define([
    'angular',
    'underscore',
    'myLibModule', // Exports an Angular module object
    'myOtherLibModule', // Exports an Angular module object
], function(angular, _) {
    angular.module('MyApp', _.pluck(unnamedArguments, 'name'));
});

当然,在RequireJS中对依赖项进行分组的方法对于这个特定的用例也足够了。

函数的
length
属性中提供了声明参数的数量

因此,您可以获得索引大于或等于此
长度的参数:

var undeclaredArgs = [].slice.call(arguments, arguments.callee.length);
如前所述,应尽可能使用对函数的引用:

var undeclaredArgs = [].slice.call(arguments, f.length);

的ES6特性(如“…和其他参数”)与您在问题中所描述的完全相同,但尚未广泛实现。有了这个特性,您可以定义函数f(foo,bar,…unnamedArguments)
。Python和Java(可能还有很多其他语言)已经有了这个功能很长时间了,所以看到JS也有这个功能就好了。@EmilLundberg TBH在ES5中创建变量函数已经很容易了,即使没有函数长度:您通常知道函数声明参数的数量。+1。永远不要使用
参数。被调用方
,只需命名函数表达式。完美!所以
define([…]),function module(angular,{…})
Array.prototype.slice.call(arguments,module.length)
是一种方法。@Bergi但是注意到了其中的问题,所以最好使用函数声明。@RobG:是的,我知道它们,但我倾向于忽略旧的。根据bug的性质,它可能会泄漏一些函数对象,但大多数代码仍按预期工作。