Array.prototype.slice.call(arguments)
首先,Array.prototype.slice.call(arguments)可以把带length属性的对象转换为数组,看两个例子
1、普通对象
var a={length:2,0:'first',1:'second'}; Array.prototype.slice.call(a);// ["first", "second"] var a={length:2}; Array.prototype.slice.call(a);// [undefined, undefined]
2、arguments
var restArr = function (){ console.log(Array.prototype.slice.call(arguments)); // ["aa","bb","cc"] } restArr("aa","bb","cc");
那么,Array.prototype.slice.call(arguments)内部是如何实现或者说怎么实现数组转换的呢?
Array.prototype.slice = function(start,end){ var result = new Array(); start = start || 0; end = end || this.length; //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键 for(var i = start; i < end; i++){ result.push(this[i]); } return result; }
call的作用的是什么,想必都知道是改变this的指向,也就是作用域,那么当Array.prototype.slice.call(),在上面例子中的this指向的是哪个?就是call出来的arguments,那么下面的push就是转为数组的过程,就这么理解就对了,想必也知道Array.prototype.slice.call(arguments)转数组的过程了,不要深究,理解就行。