复制arguments对象的子集,而不使用显式循环

pyo*_*yon 3 javascript jquery coding-style

我有一个JavaScript函数,它需要两个必需的参数,然后任意多个可选参数.

function myFunction(required1, required2) {
    var more = [];
    for (var i = 2; i < arguments.length; ++i)
        more.push(arguments[i]);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在,我喜欢通过我的所有代码强制执行一致的样式.由于我的网站使用jQuery,而jQuery喜欢使用$.each$.map覆盖显式循环,我想摆脱显式循环myFunction.但是,我不能使用$.each或者$.map因为我不想复制整个参数列表,以免我执行以下操作:

var more = $.map(arguments, function(argument, index) {
    return (index < 2) ? null : [argument];
});
Run Code Online (Sandbox Code Playgroud)

当然,这是一个非常糟糕的主意,因为测试是否index < 2在每次迭代中都是不必要的.

我真的希望能够arguments使用标准函数将对象的子集提取到新数组中.但是,因为arguments不是数组,我不能slice.

有没有其他方法我可以提取到一个数组所有参数,但前两个,没有使用显式循环,并没有失去效率?

sdl*_*rhc 10

使用slice方法:

var optional_arguments = Array.prototype.slice.call(arguments, 2);
Run Code Online (Sandbox Code Playgroud)

我们必须从中调用它,Array.prototype因为即使它arguments是类似数组,它实际上也没有slice方法.

  • `Array.prototype.slice.call`稍微有点效率(在概念上更准确),因为我不需要创建一个空数组. (3认同)