前端复习--Array.prototype.slice.call(arguments)

本文解析了如何使用Array.prototype.slice.call将类数组转化为真正的数组,并解释了这种方法的工作原理及为何有效。

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

Array.prototype.slice.call(arguments)可以将 类数组 转化为真正的数组。面试中常常问到此,但是,为什么呢?

1 首先是Array同Object,Number等 都是一种数据类型的名字,同时Array又是构造函数,每个构造函数都有一个prototype属性指向其原型对象。其原型对象上能取到slice方法。

2 什么是类数组(有length属性,属性值为数字;其他属性值为数字‘0’,‘1’,等)

var myobject ={ // array-like collection
    length: 4,
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three'
}

arguments

var uls = document.getElementsByTagName("ul") // array-like collection

3 slice本来只是Array和 String的方法,为什么可以直接用在类数组上面?

小伙子,我们到了该去看看Array.prototype.slice源码的时候了!

查看 V8 引擎 array.js 的源码,可以将 slice 的内部实现简化为:

function slice(start, end) { 
var len = ToUint32(this.length), result = []; 
for(var i = start; i < end; i++) { 
    result.push(this[i]); 
} 
    return result; 
}     
可以看出,slice 并不需要 this 为 array 类型,只需要有 length 属性即可。并且 length 属性可以不为 number 类型,当不能转换为数值时,ToUnit32(this.length) 返回 0.
根据以上结论可以得出:fakeArray01被转换成了lenth为2的数组,其值都被初始化为
4.多种调用格式u

[].slice.call(arguments)

Array.prototype.slice.call(arguments) //最高效

new Array().prototype.slice.call(arguments)

//The one remaining question is why we're calling slice() on the prototype object of Array instead of an array instance. The reason is because this is the most direct route to accessing the slice() method of Array when that's all we're interested in; we could have first created an array instance, but that's less efficient and arguably more abstruse:


参考:
http://wenzhixin.net.cn/2014/08/03/slice_arguments

http://www.javascriptkit.com/javatutors/arrayprototypeslice.shtml



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值