Array.prototype.slice.call(arguments)
能將具備length屬性的對象轉成數組,除了IE下的節點集合(由於ie下的dom對象是以com對象的形式實現的,js對象與com對象不能進行轉換)
如:javascript
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");
補充:
將函數的實際參數轉換成數組的方法java
方法一:var args = Array.prototype.slice.call(arguments);
數組
方法二:var args = [].slice.call(arguments, 0);
dom
方法三:函數
var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); }
最後,附個轉成數組的通用函數spa
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; } }