我发现Array
对象和Array.prototype
都有length
属性。我对使用Array.length
属性感到困惑。你如何使用它?
Console.log(Object.getOwnpropertyNames(Array));//As per Internet Explorer
输出:
length,arguments,caller,prototype,isArray,
Prototype
和isArray
是可用的,但如何使用length
属性?
我发现Array
对象和Array.prototype
都有length
属性。我对使用Array.length
属性感到困惑。你如何使用它?
Console.log(Object.getOwnpropertyNames(Array));//As per Internet Explorer
输出:
length,arguments,caller,prototype,isArray,
Prototype
和isArray
是可用的,但如何使用length
属性?
Array
是一个构造函数。
所有的函数都有一个 length
属性,该属性返回函数定义中声明的参数数量。
Array.length
是函数 Array()
接受的参数数量,而 Array.prototype.length
是一个实例方法,可以获取数组的长度。当您检查 ['foo'].length
时,实际上是使用数组 ['foo']
作为 this
参数来检查 Array.prototype.length
var myArray = ['a','b','c']
console.log(myArray.length); //logs 3
Array
实例,它会通过JavaScript使用原型继承从Array.prototype
继承所有属性。function MyClass() {
this.foo = Math.random();
}
MyClass.prototype.getFoo = function() {
return this.foo;
}
// Get and log
var bar = new MyClass();
console.log(bar.getFoo());
这声明了一个类的函数(作为构造函数)。该函数为类的每个实例提供原型。当我们将一个方法 (getFoo
) 分配给该原型时,类的每个实例都将拥有该方法。
然后您可以在实例上调用该方法,并将其应用于该类包含的数据。对于数组,length
属性将获取您调用它的数组的长度:
[1, 2, 3, 4].length == 4; // Every array has a length
然而,由于函数的行为很大程度上类似于对象,并且可能具有自己的属性,因此Array
本身可能具有属性。这就是在使用Array.length
时看到的情况,它获取Array
(构造函数)函数期望接收的参数数量。每个函数都有一个length
属性。
Array.length
提供了在 Array
函数定义中声明的参数数量。由于 Array 函数定义只有一个 size
参数,因此它将返回 1,无论您的数组内容如何。
Array.prototype.length
提供了数组数据中元素的数量。它取决于数组内容。
var arr=new Array();
console.log(Array.length);//returns 1
console.log(arr.length);//returns 0 as array has 0 elements