有没有办法只得到未命名的参数?

Emi*_*erg 3 javascript ecmascript-5

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

function f(foo, bar) {
    console.log(arguments);
}
f(1, '2', 'foo'); // [1, "2", "foo"]
Run Code Online (Sandbox Code Playgroud)

有没有办法获取未命名的参数,所以你可以做这样的事情?

function f(foo, bar) {
    console.log('foo:', foo, 'bar:', bar, 'the rest:', unnamedArguments);
}
f(1, '2', 'foo'); // foo: 1 bar: "2" the rest: ["foo"]
Run Code Online (Sandbox Code Playgroud)

但为什么?

一个真实的用例是将Angular模块作为参数注入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]);
});
Run Code Online (Sandbox Code Playgroud)

由于模块依赖关系列表可能会非常大,因此很快变得非常麻烦.虽然我可以解决它

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));
});
Run Code Online (Sandbox Code Playgroud)

这也很麻烦,如果我可以这样做,那就太好了:

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

当然,在RequireJS中对依赖关系进行分组的方法也足以满足此特定用例.

Den*_*ret 8

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

所以你可以得到索引大于或等于这个的参数length:

var undeclaredArgs = [].slice.call(arguments, arguments.callee.length);
Run Code Online (Sandbox Code Playgroud)

由于您无法arguments.callee在ES5开始时以严格模式使用,因此应尽可能使用对该函数的引用:

var undeclaredArgs = [].slice.call(arguments, f.length);
Run Code Online (Sandbox Code Playgroud)

  • @ Bergi-但注意到[*IE*中的命名函数表达式](http://kangax.github.io/nfe/#jscript-bugs)的问题,所以最好使用函数声明. (2认同)