gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:24:17 25 4
gpt4 key购买 nike

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

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"]

但为什么呢?

一个真实的用例是将 Angular 模块作为参数注入(inject)到 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 属性中提供。

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

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

作为you can't use arguments.callee in strict mode starting from ES5 ,您应该尽可能使用对函数的引用:

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

关于javascript - 有没有办法只获取未命名的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25264373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com