Array.prototype.slice.call()方法

先将该方法拆分成两部分:
1、Array.prototype.slice()
该方法 返回 一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象,且原数组不会被修改。
根据以上定义,我们可以猜测下该方法的实现原理:

Array.prototype.slice=function(start,end){
var result=new Array();
start=start||0; //两竖杆前的start是一个注释标签
end=end||this.length; //this指向调用对象,当用了call后,能够改变this指向,也就是指向传进来的对象,这是关键
for(var i=start;i<end;i++){
result.push(this[i]);
}
return result;
}


2、call()
例:
var a=function(){
console.log(this); //'littledu'
console.log(typeof this); //Object
console.log(this instanceof String); //true
}
a.call('littledu');
个人看法:该方法用改变this的指向,比如以上例子,this指向改为'littledu'对象



真正原理
例1:
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)); //[]


例2:
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');



补充:
将函数的实际参数转换成数组的方法
法一:var args=Array.prototype.slice.call(arguments);
法二:var args=[].slice.call(arguments,0);
法三:
var args=[];
for(var i=0;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<length;i++){
arr.push(s[i]);
}
return arr;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_39034984/article/details/80723370