将HTMLCollection/NodeList/伪数组转换成数组
2011-03-12 17:15
441 查看
这里把符合以下条件的对象称为伪数组(ArrayLike)
1,具有length属性
2,按索引方式存储数据
3,不具有数组的push,pop等方法
如
1,function内的arguments 。
2,通过document.forms,Form.elements,document.styleSheets, Select.options,document.getElementsByName ,document.getElementsByTagName ,childNodes/children 等方式获取的集合(HTMLCollection,NodeList)等。
3,特殊写法的对象 ,如
它们不具有数组的一些方法如push, pop, shift, join等。有时候需要将这些伪数组转成真正的数组,这样可以使用push, pop等方法。以下是工具函数makeArray
以下分别测试以上三种伪数组
1,具有length属性
2,按索引方式存储数据
3,不具有数组的push,pop等方法
如
1,function内的arguments 。
2,通过document.forms,Form.elements,document.styleSheets, 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);
相关文章推荐
- 将HTMLCollection/NodeList/伪数组转换成数组
- js中将HTMLCollection/NodeList/伪数组转换成数组的代码
- 将HTMLCollection/NodeList/伪数组转换成数组
- 将HTMLCollection/NodeList/伪数组转换成数组的实现方法
- 将HTMLCollection/NodeList/伪数组转换成数组
- 将HTMLCollection/NodeList/伪数组转换成数组
- 数组与collection(集合类)之间的转换
- Collection转换为数组时的API使用不当
- HTML(DOM)与JavaScript嵌套数组之间相互转换
- Collection 集合添加元素转换成数组
- js--NodeList转换成数组的方法
- List、Set、数组之间的转换 数组转Collection
- Collection和数组之间的转换
- 如何转换数组 List to ObservableCollection
- HTML(DOM)与JavaScript嵌套数组之间相互转换
- 数组和Collection之间的转换
- 把传过来的Object对象转换成Collection类型的对象。isArray()方法,判定此Class对象是否表示一个数组类。java.lang.reflect.Array 对任意数组进行操作
- php字符串和数组间的转换