A question about JavaScript's slice and splice methods

后端 未结 3 1205
死守一世寂寞
死守一世寂寞 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:40


    The actual code from that linked answer is:

    var args = Array.prototype.slice.call(arguments, 1);
    

    i.e. "slice", not "splice"

    First of all, the slice method is often used to make a copy of the array it's called on:

    var a = ['a', 'b', 'c'];
    var b = a.slice();  // b is now a copy of a
    var c = a.slice(1); // c is now ['b', 'c']
    

    So the short answer is that the code is basically emulating:

    arguments.slice(1); // discard 1st argument, gimme the rest
    

    However you can't do that directly. The special arguments object (available inside the execution context of all JavaScript functions), although Array-like in that it supports indexing via the [] operator with numeric keys, is not actually an Array; You can't .push onto it, .pop off it, or .slice it, etc.

    The way the code accomplishes this is by "tricking" the slice function (which again is not available on the arguments object) to run in the context of arguments, via Function.prototype.call:

    Array.prototype.slice // get a reference to the slice method
                          // available on all Arrays, then...
      .call(              // call it, ...
        arguments,        // making "this" point to arguments inside slice, and...
        1                 // pass 1 to slice as the first argument
      )
    

    Array.prototype.slice.call(arguments).splice(1) accomplishes the same thing, but makes an extraneous call to splice(1), which removes elements from the array returned from Array.prototype.slice.call(arguments) starting at index 1 and continuing to the end of the array. splice(1) doesn't work in IE (it's technically missing a 2nd parameter telling it how many items to remove that IE and ECMAScript require).

提交回复
热议问题