一个关于 JavaScript 的 slice 和 splice 方法的问题 [英] A question about JavaScript's slice and splice methods
问题描述
我遇到了以下代码:
var f = function () {
var args = Array.prototype.slice.call(arguments).splice(1);
// some more code
};
基本上,args
中的结果是一个数组,它是 arguments
的副本,没有第一个元素.
Basically, the result in args
is an array that is a copy of the arguments
without its first element.
但我无法确切理解的是为什么 f
的 arguments
(这是一个将函数的输入参数保存到类似数组的对象中的对象)对象正在传递给 slice
方法以及 slice(1)
如何移除第一个元素(位于索引 0).
But what I can't understand exactly is why f
's arguments
(which is an object that holds the function's inputted arguments into an array-like object) object is being passed to the slice
method and how slice(1)
is removing the first element (positioned at index 0).
谁能帮我解释一下?
P.S.代码来自这个部分应用函数一个>
推荐答案
<注意>
来自 链接答案是:
var args = Array.prototype.slice.call(arguments, 1);
即切片",而不是拼接"
</注意>
i.e. "slice", not "splice"
</Note>
首先,slice
方法常用于复制它被调用的数组:
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
但是你不能直接这样做.特殊arguments
对象(在所有 JavaScript 函数的执行上下文),尽管 Array-like 支持通过带有数字键的 []
运算符进行索引,但实际上并不是一个数组;你不能.push
到它上面,.pop
关闭它,或者.slice
它,等等.
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.
代码实现这一点的方式是通过欺骗"slice
函数(该函数在 arguments
对象上同样不可用)在上下文中运行 参数
,通过 <代码>Function.prototype.call:
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)
完成同样的事情,但是对 splice(1)
进行了一个无关的调用,它从 Array.prototype.slice.call(arguments)
返回的数组中删除 个元素,从索引 1
开始并继续到数组的末尾.splice(1)
在 IE 中不起作用(从技术上讲,它缺少第二个参数,告诉它要删除 IE 和 ECMAScript 需要多少项).
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).
这篇关于一个关于 JavaScript 的 slice 和 splice 方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!