A question about JavaScript's slice and splice methods

后端 未结 3 1209
死守一世寂寞
死守一世寂寞 2020-12-24 13:52

I came across the following code:

var f = function () {
    var args = Array.prototype.slice.call(arguments).splice(1);

    // some more code 
};

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 14:38

    The returned value of a splice is an array of the elements that were removed, but the original array (or array-like object), is truncated at the splice index.

    Making a copy with slice preserves the original arguments array, presumably for use later in the function.

    In this case the same result can be had with args = [].slice.call(arguments, 1)

    function handleArguments(){
     var A= [].slice.call(arguments).splice(1);
     //arguments is unchanged
     var s= 'A='+A+'\narguments.length='+arguments.length;
    
     var B= [].splice.call(arguments, 1);
     // arguments now contains only the first parameter
     s+= '\n\nB='+B+'\narguments.length='+arguments.length;
     return s;
    }
    
    // test
    alert(handleArguments(1, 2, 3, 4));
    
    returned value:
    //var A= [].slice.call(arguments).splice(1);
    A=2,3,4
    arguments.length=4
    
    //var B= [].splice.call(arguments, 1);
    B=2,3,4
    arguments.length=1
    

提交回复
热议问题