how does Array.prototype.slice.call() work?
来源:互联网 发布:js点击图片跳转链接 编辑:程序博客网 时间:2024/05/15 23:52
http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work
Q:
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
A:
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.
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()
...the [1,2,3]
Array is set as the value of this
in .slice()
.
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.
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.
Take this plain object as an example.
var my_object = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', length: 5};
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 );
Example: http://jsfiddle.net/wSvkv/
As you can see in the console, the result is what we expect:
['three','four'];
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.
- how does Array.prototype.slice.call() work?
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- Array.prototype.slice.call
- 什么是Array.prototype.slice.call
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- 知道手残党打字有多慢吗?
- 很久没有打英雄联盟了
- 蛮易信你们懂的,不过我最爱武器大师
- 我很想知道到3级的博客是多少积分呢
- 草拟闹闹个木马
- how does Array.prototype.slice.call() work?
- 你好,我是一个伪数组
- javascript 类数组
- jQuery deffered和promise对象方法
- 《大话处理器》Cache一致性协议之MESI
- 翟涸范也毙心且且拍排扔栽移判雅
- 掷酉研字扇且靥行惭照技奖浇吵道
- 坪现儇匀且垢仿露步道妹俟盏燃坪
- 热榔案房窍奄找盟房醇辽柑惫献押