您的位置:首页 > Web前端

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

2016-09-19 14:22 507 查看
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 whywe're calling 
slice()
 on the prototypeobject of Array instead of an array instance. The reason is because this is the most direct route to accessing the 
slice()
 methodof 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

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: