Array.prototype.slice.call(arguments)

本文通过实例解释了如何使用Array.prototype.slice.call将类数组对象转换为真正的数组。这在处理函数参数等类数组对象时非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    理解Array.prototype.slice.call(arguments)是如何工作的?

    我直接上例子,我就不翻译了,真是怕翻译错了。

   

var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);
var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);
var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
console.log(Array.prototype.slice.call(a,0));//[]

function test(){
  console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
  console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
}
test("a","b","c");

   arguments本身不是一个数组,可以说是有length属性的一个对象(类数组对象),所以需要将其变通,改造成一个数组。

   JS数组用法,参考此链接

 

 

   stackoverflow:原帖

 

    What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates the 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 is the this value of .slice(). Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as though it was working with an Array.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值