解析 Array.prototype.slice.call(arguments,0)

Array.prototype.slice.call(arguments,0) 经常会看到这段代码用来处理函数的参数

网上很多复制粘帖说:Array.prototype.slice.call(arguments)能将具有length属性的对象 转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)

关键点:

1、Array是构造函数

2、arguments是类数组对象(缺少很多数组的方法)

3、call让一个对象调用另一个对象的方法。你可以使用call()来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)

4、 slice从一个数组中切割,返回新的数组,不修改切割的数组

so,其实本质就是arguments这个对象使用了数组的slice这个方法,得到了参数构成的数组(也可以用apply)。

Array.prototype.slice.call(arguments, [0, arguments.length])

//使用prototype只是因为Array是构造函数

Array.prototype.slice.call([1,2,3,4,5],0)//  [1, 2, 3, 4, 5]

[].slice.call([1,2,3,4,5],1)// [2, 3, 4, 5]


//没有length的对象
var a={length:2, 0:'first', 1:'second'};
Array.prototype.slice.call(a);//  ["first", "second"]

var a={length:2, 0:'first', 1:'second'};
Array.prototype.slice.call(a,1);//  ["second"]

var a={0:'first', 1:'second'};
Array.prototype.slice.call(a,1);//  []

猜你喜欢

转载自www.cnblogs.com/papi/p/9234964.html
今日推荐