将HTMLCollection/NodeList/伪数组转换成数组

这里把符合以下条件的对象称为伪数组(ArrayLike)


1,具有length属性
2,按索引方式存储数据
3,不具有数组的push,pop等方法

1,function内的arguments 。
2,通过document.forms,Form.elements,Select.options,document.getElementsByName() ,document.getElementsByTagName() ,childNodes/children 等方式获取的集合(HTMLCollection,NodeList)等。

它们不具有数组的一些方法如push, pop, shift, join等。有时候需要将这些伪数组转成真正的数组,这样可以使用push, pop等方法。以下是工具函数makeArray

var makeArray = function(obj){
    return Array.prototype.slice.call(obj,0);
}

以下分别测试以上伪数组:

//定义一个函数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);
原文地址:https://www.cnblogs.com/weekend001/p/3659675.html