而对于一个普通的对象来讲,若是它的全部property名均为正整数,同时也有相应的length属性,那么虽然该对象并非由Array构造函数所建立的,它依然呈现出数组的行为,在这种状况下,这些对象被称为“类数组对象”。总而言之,具备如下两点的对象:javascript
如下是一个简单的类数组对象:
var o = {0:42, 1:52, 2:63, length:3} console.log(o);
类数组的其余常见状况:如下是一个简单的类数组对象:
//1.在ECMAScript 5标准中,字符串string就是一个只读的类数组对象: //2.在浏览器环境中,DOM方法的返回结果。如:document.getElementsByTagName()语句返回的就是一个类数组对象。 //3.在function调用中,function代码内的arguments变量(保存传入的参数)也是一个类数组对象。
与普通对象不一样的是,类数组对象拥有一个特性:能够在类数组对象上应用数组的操做方法。java
好比,在ECMAScript 5标准中,能够用如下方法来将上面的对象o合并成字符串:node
console.log(Array.prototype.join.call(o));//"42,52,63"
也能够在类数组对象上使用slice()方法获取子数组:es6
console.log(Array.prototype.slice.call(o, 1, 2));//[52]
《javascript权威指南》上给出了代码用来判断一个对象是否属于“类数组”。以下:segmentfault
1 // Determine if o is an array-like object. 2 // Strings and functions have numeric length properties, but are 3 // excluded by the typeof test. In client-side JavaScript, DOM text 4 // nodes have a numeric length property, and may need to be excluded 5 // with an additional o.nodeType != 3 test. 6 function isArrayLike(o) { 7 if (o && // o is not null, undefined, etc. 8 typeof o === 'object' && // o is an object 9 isFinite(o.length) && // o.length is a finite number 10 o.length >= 0 && // o.length is non-negative 11 o.length===Math.floor(o.length) && // o.length is an integer 12 o.length < 4294967296) // o.length < 2^32 13 return true; // Then o is array-like 14 else 15 return false; // Otherwise it is not 16 }
var a = {'0':1,'1':2,'2':3,length:3}; var arr = Array.prototype.slice.call(a);//arr=[1,2,3]
1 // 伪数组转化成数组 2 var makeArray = function(obj) { 3 if (!obj || obj.length === 0) { 4 return []; 5 } 6 // 非伪类对象,直接返回最好 7 if (!obj.length) { 8 return obj; 9 } 10 // 针对IE8之前 DOM的COM实现 11 try { 12 return [].slice.call(obj); 13 } catch (e) { 14 var i = 0, 15 j = obj.length, 16 res = []; 17 for (; i < j; i++) { 18 res.push(obj[i]); 19 } 20 return res; 21 } 22 23 };
在浏览器环境中,document.getElementsByTagName()语句返回的就是一个类数组对象。
var a = document.getElementsByTagName('p'); var arr = ...a;
在ECMAScript 5标准中,字符串string就是一个只读的类数组对象:
var arr = ...“abc”;//['a', 'b', 'c'];
注意:es8新增扩展运算符对对象的支持。
javascript类数组:http://www.javashuo.com/article/p-pojgutlf-x.html数组