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]
首先,slice有兩個用法,一個是String.slice,一個是Array.slice,第一個返回的是字符串,第二個返回的是數組,這里我們看第2個。
Array.prototype.slice.call(arguments)能夠將arguments轉成數組,那么就是arguments.toArray().slice();到這里,是不是就可以說Array.prototype.slice.call(arguments)的過程就是先將傳入進來的第一個參數轉為數組,再調用slice? ? 再看call的用法,如下例子 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'); 可以看出,call了后,就把當前函數推入所傳參數的作用域中去了,不知道這樣說對不對,但反正this就指向了所傳進去的對象就肯定的了。 到這里,基本就差不多了,我們可以大膽猜一下slice的內部實現,如下 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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jQuery编写插件
- 下一篇: iOS警告-This block dec