`Array.prototype.slice.call` 是如何工作的? [英] How does `Array.prototype.slice.call` work?

查看:24
本文介绍了`Array.prototype.slice.call` 是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它用于使 arguments 成为真正的 Array,但我不明白使用 Array.prototype.slice.call(参数);.

解决方案

幕后发生的事情是,当 .slice() 被正常调用时,this 是一个Array,然后它只是迭代那个 Array,并完成它的工作.

.slice() 函数中的 this 如何是一个数组?因为当你这样做时:

object.method();

...object 自动成为 method()this 的值.所以:

[1,2,3].slice()

...[1,2,3]数组被设置为.slice()this的值.

<小时>

但是,如果您可以用其他东西代替 this 值呢?只要你替换的任何东西都有一个数字 .length 属性,和一堆数字索引的属性,它应该可以工作.这种类型的对象通常称为类数组对象.

.call().apply() 方法让你手动设置this的值在一个函数中.因此,如果我们将 .slice()this 的值设置为类数组对象.slice() 只会假设它正在处理一个数组,并且会做它的事情.

以这个普通对象为例.

var my_object = {'0': '零','1': '一个','2': '二','3': '三','4': '四',长度:5};

这显然不是一个Array,但是如果你能把它设置为.slice()this值,那么它就可以工作了,因为它看起来足够了就像一个用于 .slice() 正常工作的数组.

var sliced = Array.prototype.slice.call( my_object, 3 );

示例: http://jsfiddle.net/wSvkv/

正如您在控制台中看到的,结果正是我们所期望的:

['三','四'];

这就是当您将 arguments 对象设置为 .slice()this 值时会发生的情况.因为 arguments 有一个 .length 属性和一堆数字索引,.slice() 就好像它正在工作一样继续工作一个真正的数组.

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);.

解决方案

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.

这篇关于`Array.prototype.slice.call` 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆