【问题标题】:Array.length vs Array.prototype.length [duplicate]Array.length vs Array.prototype.length [重复]
【发布时间】:2015-01-30 16:20:40
【问题描述】:

我发现Array 对象和Array.prototype 都具有length 属性。我对使用 Array.length 属性感到困惑。你是怎么用的?

Console.log(Object.getOwnpropertyNames(Array));//As per Internet Explorer

输出:

length,arguments,caller,prototype,isArray,

PrototypeisArray 是可用的,但你如何使用 length 属性?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    Array 是一个构造函数。

    所有函数都有一个length 属性,该属性返回函数定义中声明的参数的数量。

    【讨论】:

    • 这是一个完美的答案..谢谢亲爱的先生
    【解决方案2】:

    Array.length 是函数Array() 需要多少个参数,Array.prototype.length 是一个实例方法,可以为您提供数组的长度。当您检查['foo'].length 时,您实际上是在检查Array.prototype.length,其中this 参数是您的数组['foo']

    var myArray = ['a','b','c']
    console.log(myArray.length); //logs 3

    【讨论】:

    • 我的意思是如何检查 Array.length ..我不是在谈论 Array.prototype.length..好吧,我知道了,我应该在函数中使用它对吗?
    • 如何检查 Array.length 的内容?为什么你会关心 Array.length?你已经知道这意味着什么了。很多人已经向您解释了它的含义。您需要停下来阅读人们提供的答案。也许想一想。
    【解决方案3】:

    如果您有一个Array 的实例,它会从Array.prototype 继承所有属性,这要感谢Javascript's use of prototypical inheritance

    举个例子:

    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(构造函数)函数期望接收的参数数量。 Every function has a length property.

    【讨论】:

      【解决方案4】:

      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
      

      【讨论】:

        猜你喜欢
        • 2013-06-01
        • 2010-12-03
        • 2012-08-18
        • 1970-01-01
        • 2012-11-21
        • 2017-07-04
        • 2021-05-26
        • 1970-01-01
        相关资源
        最近更新 更多