DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 將HTMLCollection/NodeList/偽數組轉換成數組的實現方法
將HTMLCollection/NodeList/偽數組轉換成數組的實現方法
編輯:關於JavaScript     
這裡把符合以下條件的對象稱為偽數組
1,具有length屬性
2,按索引方式存儲數據
3,不具有數組的push,pop等方法


1,function內的arguments 。
2,通過document.forms,Form.elements,Select.options,document.getElementsByName() ,document.getElementsByTagName() ,childNodes/children 等方式獲取的集合(HTMLCollection,NodeList)等。
3,特殊寫法的對象 ,如
復制代碼 代碼如下:
var obj={};
obj[0] = "一";
obj[1] = "二";
obj[2] = "三";
obj.length = 3;

它們不具有數組的一些方法如push, pop, shift, join等。有時候需要將這些偽數組轉成真正的數組,這樣可以使用push, pop等方法。以下是工具函數makeArray
復制代碼 代碼如下:
var makeArray = function(obj){
return Array.prototype.slice.call(obj,0);
}
try{
Array.prototype.slice.call(document.documentElement.childNodes, 0)[0].nodeType;
}catch(e){
makeArray = function(obj){
var res = [];
for(var i=0,len=obj.length; i<len; i++){
res.push(obj[i]);
}
return res;
}
}

以下分別測試以上三種偽數組
復制代碼 代碼如下:
//定義一個函數fun,內部使用makeArray將其arguments轉換成數組
function fun(){
var ary = makeArray(arguments);
alert(ary.constructor );
}
//調用
fun(3,5);


//假設頁面上有多個段落元素p
var els = document.getElementsByTagName("p");
var ary1 = makeArray(els);
alert(ary1.constructor);


//特殊的js對象(如jquery對象)
var obj={};
obj[0] = "一";
obj[1] = "二";
obj[2] = "三";
obj.length = 3;

var ary2 = makeArray(obj);
alert(ary2.constructor);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved