js类数组对象(array-like objects)简单介绍

快乐打工仔 分类:实例代码

在一些关于javascript文章中,可能会有类数组这个名词的提及。

也有把对象当做一个数组操作的例子,看如下代码实例:

function func(a,b,c,d){
  var arr=[].slice.call(arguments);
  console.log(arr);
}
func(1,2,3,4);

上面的代码中可以将arguments对象转换为一个真正的数组,调用的是数组的slice()方法。

arguments对象就是一个类数组(array-like objects)。

那么如何判断什么样的对象才是一个类数组,下面就做一下简单介绍:

网上的资料对于类数组的解释如下:

So what exactly makes an object “array-like”? The basic contract of
an array object amounts to two simple rules.
It has an integer length property in the range 0...2^32 – 1.
The length property is greater than the largest index of the object.
An index is an integer in the range 0...2^32 – 2 whose string representation
is the key of a property of the object.

从上面的文字可以看出,类数组对象主要有如下几个特征:

(1).对象要有一个属性值为整数的length属性,并且值得大小介于0到2^32 – 1之间。

(2).length属性值要大于对象的最大的index属性值。

(3).index属性是作为对象的属性的key存在的。

再来看一段代码实例:

1: "a",
  2: "b", 
  4: "c", 
  length:5
}
var arr=[].slice.call(obj);
console.log(arr)

上面的代码也可以正确执行,但是并不是所有的array对象的方法都可以被类数组对象使用。

回复

我来回复
  • 暂无回复内容