摘自:http://blog.csdn.net/i10630226
在很多時候經(jīng)扯懒睿看到Array.prototype.slice.call()方法,比如Array.prototype.slice.call(arguments)轧苫,下面講一下其原理:
1、基本講解
1.在JS里Array是一個類 slice是此類里的一個方法 ,那么使用此方法應該Array.prototype.slice這么去用
slice從字面上的意思很容易理解就是截瘸晏!(當然你不是英肓的話) 這方法如何使用呢?
arrayObj.slice(start, [end])
很顯然是截取數(shù)組的一部分。2.我們再看call
call([thisObj[,arg1[arg2[[argN]]]]])
thisObj是一個對象的方法
arrg1~argN是參數(shù)
那么Array.prototype.slice.call(arguments,1);
這句話的意思就是說把調(diào)用方法的參數(shù)截取出來抽莱。
如:
function test(a,b,c,d)
{
var arg = Array.prototype.slice.call(arguments,1);
alert(arg);
}
test("a","b","c","d"); //b,c,d
2范抓、疑惑解答
先給個例子,這是jqFloat插件里的代碼:
if (element.data('jDefined')) {
if (options && typeof options === 'object') {
methods.update.apply(this, Array.prototype.slice.call(arguments, 1));
}
} else {
methods.init.apply(this, Array.prototype.slice.call(arguments, 1));
}
多次用到 Array.prototype.slice.call(arguments, 1)食铐,不就是等于 arguments.slice(1) 嗎匕垫?像前者那樣寫具體的好處是什么?這個很多js新手最疑惑的地方虐呻。那為什么呢象泵?
因為arguments并不是真正的數(shù)組對象,只是與數(shù)組類似而已斟叼,所以它并沒有slice這個方法偶惠,而Array.prototype.slice.call(arguments, 1)
可以理解成是讓arguments轉換成一個數(shù)組對象,讓arguments具有slice()方法朗涩。要是直接寫arguments.slice(1)會報錯忽孽。
typeof arguments==="Object" //而不是 "Array"
3、真正原理
Array.prototype.slice.call(arguments)
能將具有l(wèi)ength屬性的對象轉成數(shù)組谢床,除了IE下的節(jié)點集合(因為ie下的dom對象是以com對象的形式實現(xiàn)的扒腕,js對象與com對象不能進行轉換)
如:
var a={length:2,0:'first',1:'second'};//類數(shù)組,有l(wèi)ength屬性,長度為2萤悴,第0個是first瘾腰,第1個是second
console.log(Array.prototype.slice.call(a,0));// ["first", "second"],調(diào)用數(shù)組的slice(0);
var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));//["second"],調(diào)用數(shù)組的slice(1);
var a={0:'first',1:'second'};//去掉length屬性覆履,返回一個空數(shù)組
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");
補充:
將函數(shù)的實際參數(shù)轉換成數(shù)組的方法
方法一:var args = Array.prototype.slice.call(arguments);
方法二:var args = [].slice.call(arguments, 0);
方法三:
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
最后,附個轉成數(shù)組的通用函數(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;
}
}