Array.prototype. slice.call(arguments)能夠?qū)⒕哂衛(wèi)ength屬性的對(duì)象轉(zhuǎn)化為數(shù)組,
var a={length:2,0:'first',1:'second'};
Array.prototype.slice.call(a);// ["first", "second"]
先看call的用法:
var a = function(){
console.log(this); // 'littledu'
console.log(typeof this); // Object
console.log(this instanceof String); // true
}
a.call('littledu');
call的用法就是把a(bǔ)對(duì)象的作用域作用到傳入的參數(shù)中去(也可以說傳入?yún)?shù)在a對(duì)象的環(huán)境中執(zhí)行)鬼廓。
再來看slice方法的原理:
Array.prototype.slice = function(start,end){
var result = new Array();
start = start || 0;
end = end || this.length; //this指向調(diào)用的對(duì)象,當(dāng)用了call后历筝,能夠改變this的指向,也就是指向傳進(jìn)來的對(duì)象,這是關(guān)鍵
for(var i = start; i < end; i++){
result.push(this[i]);
return result;
}
最后介紹下轉(zhuǎn)成數(shù)組的通用方法:
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]; //據(jù)說這樣比push快
}
return arr;
}
}