翻看不少框架源码,jquery和zepto等等都会有这句话
Array.prototype.slice.call
百思不得其解的咱们努力求证……javascript
基本原理java
对象函数
中的this注意这句话对象函数中的this
jquery
function test(a,b,c,d) { var arg = Array.prototype.slice.call(arguments,1); alert(arg); } test("a","b","c","d"); //b,c,d
疑惑 为何不直接用 arguments.slice(1)呢 不是同样的么,哈哈数组
Array.prototype.slice.call(arguments, 1)能够理解成是让arguments转换成一个数组对象,让arguments具备slice()方法
。要是直接写arguments.slice(1)会报错。
app
arguments 是object 不是Array ,他的原型上没有slice方法框架
真正原理dom
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");
ps
将函数的实际参数转换成数组的方法函数
var args = Array.prototype.slice.call(arguments);
var args = Array.prototype.slice.call(arguments);
var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); }
var toArray = function(s){ try{ return Array.prototype.slice.call(s); } catch(e){ var arr = []; for(var i = 0,len = s.length; i < len; i++){ //arr.push(s[i]); arr[i] = s[i]; //听说这样比push快 } return arr; } }