什么是类数组对象?
类数组对象是JS里面比较常用的一个对象,平时在操作DOM或写function的时候经常会用到,虽然对初学者来说概念比较陌生。类数组对象具有数组对象的一些属性,比如length,可以遍历(for-in不可以)但是却不能使用数组对象的方法。
最常见的类数组就是function里面的参数变量arguments,通常传递给function的参数都会被存储在一个名为arguments的类数组里面。还比如获取DOM返回的结点列表(document.getElementsByTagName(), document.forms)也是一个类数组。
function takesTwoParams(a, b){
console.log("you gave me "+arguments.length+" arguments");
for(i=0; i<arguments.length; i++){
console.log("parameter " + i + " = " + arguments[i]);
}
console.log(" your parameters were " + arguments.join(", "));
}
takesTwoParams("one","two","three");
//输出:
//you gave me 3 arguments
//parameter 0 = one
//parameter 1 = two
//parameter 2 = three
//arguments.join is not a function
由上面的列子可以看出arguments是存储function实参的一个类数组,不具有Array的一些方法。那怎么样才能使用数组的方法呢?
类数组转换成数组
因为arguments也是一个数组,因此可通过Array的原型来实现。
function takesTwoParams(a, b){
var args = Array.prototype.slice.call(arguments);
console.log(" your parameters were " + args.join(","));
}
takesTwoParams("one","two","three");// your parameters were one,two,three
Array.prototype.slice.call(arguments)能将具有length属性的对象转成长度为length的数组,除了低版本IE下的节点集合(因为低版本ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换),如下:
//有length属性
var a={length:1,0:'first',1:'second'};
Array.prototype.slice.call(a);//["first"]
var a={length:3,0:'first',1:'second'};
Array.prototype.slice.call(a);// ["first", "second", undefined]
var a={length:2};
Array.prototype.slice.call(a);// [undefined, undefined]
//没有length属性
var a={0:'first',1:'second'};
Array.prototype.slice.call(a);// []
由于IE不支持Array.prototype.slice.call,所以以下为兼容性写法:
function hybridToArray(nodes){
try{
// works in every browser except IE
var arr = Array.prototype.slice.call(nodes);
return arr;
} catch(err){
// slower, but works in IE
var arr = [],
length = nodes.length;
for(var i=0; i<length; i++){
arr.push(nodes[i]);
}
return arr;
}
}