伪数组转换为真正的数组

法1:使用es6中Array.from
var arrList=document.getElementByClassName("active");
var arr=Array.from(arrList);       //将伪数组转换为真正的数组

var args = Array.from(arguments);   //将伪数组转换为真正的数组

let arrayLike = {
  '0': 'a',
  '1': 'b',
  '2': 'c',
  length: 3
};
var arLs = Array.from(arrayLike);//将伪数组转换为真正的数组
console.log(Object.prototype.toString.call(arLs)==='[object Array]');//true

任何Iterator接口的对象,都可以用扩展运算符转为真正的数组。
var nodeList = document.querySelectorAll('div');
var array = [...nodeList];


法2:通过call改变this指针
var newArr=Array.prototype.slice.call(oP.childNodes,0);
//Array.prototype.slice复制到了oP.childNodes中,所以oP.childNodes可以使用slice的所有方法、属性,
//又因为slice(start,end)返回的是一个数组,结束位置不包括end,所以oP.childNodes返回的也是一个位置
//Array.prototype.slice.call(oP.childNodes,0):参数2是slice的截取的开始位置,省略了结束位置,即到数组的末尾


法3:使用for循环遍历
var newArr=[];
for(var i=0;i<oP.childNodes.length;i++){
newArr.push(oP.childNodes[i]);
}
console.log(newArr);  



兼容所有浏览器的写法

function convertToArray(nodes){
var arr=[];
try{
arr=Array.prototype.slice.call(nodes,0);   //针对非IE
}catch(ex){
for(var i=0;i<nodes.length;i++){
arr.push(nodes[i]);
}
}
return arr;
}



原文地址:https://www.cnblogs.com/sakura-sakura/p/6678248.html