Array.prototype.slice.call()如何工作? [英] how does Array.prototype.slice.call() work?
问题描述
我知道它用于使参数成为一个真正的数组,但我不明白使用 Array.prototype.slice.call(arguments)时会发生什么
I know it is used to make arguments a real array, but I don't understand what happens when using Array.prototype.slice.call(arguments)
推荐答案
当引发 .slice()
时会发生什么通常,这个
是一个数组,然后它只是遍历那个数组,并完成它的工作。
What happens under the hood is that when .slice()
is called normally, this
is an Array, and then it just iterates over that Array, and does its work.
如何在 .slice()
函数中,这个
是一个数组吗?因为你这样做:
How is this
in the .slice()
function an Array? Because when you do:
object.method();
... 对象
自动成为方法()
中此
的值。所以:
...the object
automatically becomes the value of this
in the method()
. So with:
[1,2,3].slice()
... [1,2,3]
数组设置为<$的值c $ c>此 in .slice()
。
...the [1,2,3]
Array is set as the value of this
in .slice()
.
但是如果你能用这个
值代替其他东西呢?只要你替换的任何东西都有一个数字 .length
属性,以及一堆属于数字索引的属性,它应该可以工作。这种类型的对象通常称为类数组对象。
But what if you could substitute something else as the this
value? As long as whatever you substitute has a numeric .length
property, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.
.call()
和 .apply()
方法让你手动设置的值
在一个功能。因此,如果我们将
的值 .slice()设置为类似数组的对象, .slice()
只是假设它正在使用数组,并且会做它的事情。
The .call()
and .apply()
methods let you manually set the value of this
in a function. So if we set the value of this
in .slice()
to an array-like object, .slice()
will just assume it's working with an Array, and will do its thing.
以此普通对象为例。
var my_object = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
length: 5
};
这显然不是数组,但如果可以将其设置为这个
的值
.slice()
,然后就可以了,因为它看起来像一个的数组.slice ()
正常工作。
This is obviously not an Array, but if you can set it as the this
value of .slice()
, then it will just work, because it looks enough like an Array for .slice()
to work properly.
var sliced = Array.prototype.slice.call( my_object, 3 );
示例: http://jsfiddle.net/wSvkv/
正如您在控制台中看到的,结果是我们的期望:
As you can see in the console, the result is what we expect:
['three','four'];
所以当你设置参数时会发生这种情况
对象为此
值 .slice()
。因为参数
有一个 .length
属性和一堆数字索引, .slice()
就像它正在处理一个真正的阵列一样。
So this is what happens when you set an arguments
object as the this
value of .slice()
. Because arguments
has a .length
property and a bunch of numeric indices, .slice()
just goes about its work as if it were working on a real Array.
这篇关于Array.prototype.slice.call()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!