天天看點

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

Array.prototype.slice.call(arguments)

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

1  var a={length:2,0:'first',1:'second' };
 2 Array.prototype.slice.call(a); //   ["first", "second"] 
3   
4  var a= {length:2 };
 5 Array.prototype.slice.call(a); //   [undefined, undefined]      

可能剛開始學習js的童鞋并不是很能了解這句為什麼能實作這樣的功能。比如我就是一個,是以,來探究一下。

首先,slice有兩個用法,一個是String.slice,一個是Array.slice,第一個傳回的是字元串,第二個傳回的是數組,這裡我們看第2個。

Array.prototype.slice.call(arguments)能夠将arguments轉成數組,那麼就是arguments.toArray().slice();到這裡,是不是就可以說Array.prototype.slice.call(arguments)的過程就是先将傳入進來的第一個參數轉為數組,再調用slice?   再看call的用法,如下例子

Array.prototype.slice.call(arguments) Array.prototype.slice.call(arguments)
1  var a = function (){
 2       console.log( this );     // 'littledu' 
3       console.log( typeof  this );       //   Object 
4       console.log( this  instanceof String);     // true 
5  }
 6 a .call('littledu');      
Array.prototype.slice.call(arguments) Array.prototype.slice.call(arguments)

可以看出,call了後,就把目前函數推入所傳參數的作用域中去了,不知道這樣說對不對,但反正this就指向了所傳進去的對象就肯定的了。 到這裡,基本就差不多了,我們可以大膽猜一下slice的内部實作,如下

Array.prototype.slice.call(arguments) Array.prototype.slice.call(arguments)
1 Array.prototype.slice = function (start,end){
 2       var result = new Array();
 3       start = start || 0 ;
 4       end = end || this .length; // this指向調用的對象,當用了call後,能夠改變this的指向,也就是指向傳進來的對象,這是關鍵
5       for ( var i = start; i < end; i++ ){
 6            result.push( this [i]);
 7       }
 8       return result;
 9 }      
Array.prototype.slice.call(arguments) Array.prototype.slice.call(arguments)

大概就是這樣吧,了解就行,不深究。

最後,附個轉成數組的通用函數

Array.prototype.slice.call(arguments) Array.prototype.slice.call(arguments)
1  var toArray = function (s){
 2      try {
 3          return Array.prototype.slice.call(s);
 4      } catch (e){
 5              var arr = [];
 6              for ( var i = 0,len = s .length; i < len; i++ ){
 7                  //arr.push(s[i]); 
                   arr[i] = s[i]; //據說這樣比push快
 8              }
 9               return arr;
 10      }
 11 }      

繼續閱讀