javascript类数组

一、类数组定义:

而对于一个普通的对象来说,如果它的所有property名均为正整数,同时也有相应的length属性,那么虽然该对象并不是由Array构造函数所创建的,它依然呈现出数组的行为,在这种情况下,这些对象被称为“类数组对象”。总而言之,具有以下两点的对象:

  • 拥有length属性,其它属性(索引)为非负整数
  • 不具有数组所具有的方法

类数组示例:

以下是一个简单的类数组对象:
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变量(保存传入的参数)也是一个类数组对象。

二、类数组表现

与普通对象不同的是,类数组对象拥有一个特性:可以在类数组对象上应用数组的操作方法。

比如,在ECMAScript 5标准中,可以用以下方法来将上面的对象o合并成字符串:

console.log(Array.prototype.join.call(o));//"42,52,63"

也可以在类数组对象上使用slice()方法获取子数组:

console.log(Array.prototype.slice.call(o, 1, 2));//[52]

三、类数组判断:

《javascript权威指南》上给出了代码用来判断一个对象是否属于“类数组”。如下:

 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 }

四、类数组对象转化为数组的几种方式:

方式一:利用数据原型方法Array.prototype.slice.call(arguments)

var a = {'0':1,'1':2,'2':3,length:3};
var arr = Array.prototype.slice.call(a);//arr=[1,2,3]

方式二:es5之前利用循环遍历

 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 };

方式三:es6新增扩展运算符

在浏览器环境中,document.getElementsByTagName()语句返回的就是一个类数组对象。
var a = document.getElementsByTagName('p');
var arr = ...a;
在ECMAScript 5标准中,字符串string就是一个只读的类数组对象:


var arr = ...“abc”;//['a', 'b', 'c'];
注意:es8新增扩展运算符对对象的支持。

javascript类数组:https://segmentfault.com/a/1190000000415572