开发者

Copying a subset of the arguments object, without using an explicit loop

I have a JavaScript function that takes two required parameters and then arbitrarily many optional parameters.

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

Now, I like enforcing a consistent style through all my code. Since my site uses jQuery, and jQuery favors using $.each and $.map over explicit loops, I want to get rid of the explicit loop in myFunction. However, I cannot use either $.each or $.map because I don't want to copy the whole argument list, lest I do the following:

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

Which is, of course, a very bad idea, because testing whether index < 2 in every iteration is unnecessary.

I would really like to be able to extract a subset of the arguments object into a new array, using a standard function. However, because arguments is not an array, I cannot slice it.

Is there any other way I could extract into an array all arguments but the two first ones, without using 开发者_StackOverflow社区an explicit loop, and without losing efficiency?


Using the slice method:

var optional_arguments = Array.prototype.slice.call(arguments, 2);

We have to call it from Array.prototype because, even though arguments is array-like, it doesn't actually have a slice method.


The arguments of a function can be treated like an array with jQuery, for instance the following works perfectly fine:

function something(ar1,ar2){
    var args = $(arguments).slice(2);
    $(args).each(function(i){
        $('#stuff').append(args[i]+'<br />');
    });
}
$(function(){
    something('one','two','three','four');
});

And to tailor it to your function above it would look like this:

function myFunction(required1, required2) {
    var more = [];
    var args = $(arguments).slice(2);
    $(args).each(function(i){
        more.push(args[i]);
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜