理解Array.prototype.slice.call(arguments)


在很多時候經常看到Array.prototype.slice.call()方法,比如Array.prototype.slice.call(arguments),下面講一下其原理:

1、基本講解

  • 1.在js里Array是一個類 slice是此類里的一個方法 ,那么使用此方法應該Array.prototype.slice這么去用 
    slice從字面上的意思很容易理解就是截取(當然你不是英肓的話) 這方法如何使用呢? 
    arrayObj.slice(start, [end]) 很顯然是截取數組的一部分。

  • 2.我們再看call

 call([thisObj[,arg1[arg2[[argN]]]]]) 

thisObj是一個對象的方法 
arrg1~argN是參數

那么Array.prototype.slice.call(arguments,1);這句話的意思就是說把調用方法的參數截取出來。 
如:

 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並不是真正的數組對象,只是與數組類似而已,所以它並沒有slice這個方法,而Array.prototype.slice.call(arguments, 1)可以理解成是讓arguments轉換成一個數組對象,讓arguments具有slice()方法。要是直接寫arguments.slice(1)會報錯。

typeof arguments==="Object" //而不是 "Array"

 

3、真正原理

Array.prototype.slice.call(arguments)能將具有length屬性的對象轉成數組,除了IE下的節點集合(因為ie下的dom對象是以com對象的形式實現的,js對象與com對象不能進行轉換) 
如:

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");

 

補充: 
將函數的實際參數轉換成數組的方法

方法一: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; } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM