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的童鞋並非很能理解這句爲何能實現這樣的功能。好比我就是一個,因此,來探究一下。html
首先,slice有兩個用法,一個是String.slice,一個是Array.slice,第一個返回的是字符串,第二個返回的是數組,這裏咱們看第2個。數組
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');
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 }
大概就是這樣吧,理解就行,不深究。dom
最後,附個轉成數組的通用函數函數
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 }
轉:http://www.cnblogs.com/littledu/archive/2012/05/19/2508672.html學習