Copying a subset of an argument 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 to apply a consistent style across all my code. Since my site is using jQuery, jQuery and supports the use $.eachand $.mapfor obvious cycles, I want to get rid of the apparent cycle myFunction. However, I cannot use either $.each, or $.map, because I do not want to copy the entire list of arguments, so as not to do the following:

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

This, of course, is a very bad idea, because checking that index < 2every iteration is not required.

arguments , . , arguments , slice .

, , , ?

+3
2

slice:

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

Array.prototype, , arguments , slice.

+10

jQuery, , :

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

, :

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

All Articles