在不少時候常常看到Array.prototype.slice.call()方法,好比Array.prototype.slice.call(arguments),下面講一下其原理:javascript
1.在js裏Array是一個類 slice是此類裏的一個方法 ,那麼使用此方法應該Array.prototype.slice這麼去用
slice從字面上的意思很容易理解就是截取(固然你不是英肓的話) 這方法如何使用呢? arrayObj.slice(start, [end])
很顯然是截取數組的一部分。java
2.咱們再看call數組
call([thisObj[,arg1[arg2[[argN]]]]])
thisObj是一個對象的方法
arrg1~argN是參數app
那麼Array.prototype.slice.call(arguments,1);
這句話的意思就是說把調用方法的參數截取出來。
如:dom
function test(a,b,c,d) { var arg = Array.prototype.slice.call(arguments,1); alert(arg); } test("a","b","c","d"); //b,c,d
先給個例子,這是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新手最疑惑的地方。那爲何呢?ui
由於arguments並非真正的數組對象,只是與數組相似而已,因此它並無slice這個方法,而Array.prototype.slice.call(arguments, 1)
能夠理解成是讓arguments轉換成一個數組對象,讓arguments具備slice()方法。要是直接寫arguments.slice(1)會報錯。this
typeof arguments==="Object" //而不是 "Array"
Array.prototype.slice.call(arguments)
能將具備length屬性的對象轉成數組,除了IE下的節點集合(由於ie下的dom對象是以com對象的形式實現的,js對象與com對象不能進行轉換)
如:lua
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");
補充:
將函數的實際參數轉換成數組的方法spa
方法一: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]); }
最後,附個轉成數組的通用函數
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; } }