Array.prototype.slice.call()方法詳解

在不少時候常常看到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是參數 markdown

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

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插件裏的代碼:dom

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)會報錯。ui

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

三、真正原理

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

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

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

方法一: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;
    }
}
相關文章
相關標籤/搜索