我遇到以下代码:

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

    // some more code
};

基本上,args中的结果是一个数组,它是arguments的副本,没有第一个元素。

但是我无法确切理解的是为什么将farguments(将函数的输入参数保存到类似数组的对象中的对象)对象传递给slice方法,以及slice(1)如何删除第一个元素(已定位)在索引0处)。

谁能帮我解释一下吗?

附言代码来自此partial application function

最佳答案


linked answer的实际代码是:

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

即“切片”,而不是“接合”


首先,slice方法通常用于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']

因此,简短的答案是代码基本上是在模拟:
arguments.slice(1); // discard 1st argument, gimme the rest

但是,您不能直接这样做。 special arguments object(可在所有JavaScript函数的执行上下文中找到),尽管类似于Array,但它通过带有数字键的[]运算符支持索引,但实际上不是Array;您无法在其上.push,关闭.pop或对其进行.slice等。

代码完成此操作的方式是通过 slice “打勾” arguments函数(该函数再次在arguments对象上不可用)在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)完成相同的操作,但是对splice(1)进行了多余的调用,该操作从Array.prototype.slice.call(arguments)返回的数组中删除了元素,该数组从1开始,从索引splice(1)开始,一直持续到数组的末尾。 ojit_code在IE中不起作用(从技术上讲,它缺少第二个参数,该参数告诉它要删除IE和ECMAScript要求删除多少项)。

关于javascript - 有关JavaScript的slice和splice方法的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1777705/

10-12 00:13
查看更多