【问题标题】:Assigning properties to array gives length 0 in javascript [duplicate]将属性分配给数组在javascript中给出长度0 [重复]
【发布时间】:2022-02-05 16:30:55
【问题描述】:

我们可以将属性分配给数组,但是为什么在这种情况下长度为0? 见附件代码

var person = []
person.fname = "Mr. Brown"
person.lname = "White"
person.length // gives 0 why?

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

the specification:

Array 实例的“length”属性是一个数据属性,其值在数值上始终大于每个名称为数组索引的可配置自有属性的名称。

整数索引是字符串值的属性键,它是规范的数字字符串(参见 7.1.21),其数值为 +0? 或正整数 Number ≤ ?(253 - 1)。数组索引是一个整数索引,其数值 i 在 +0? ≤ i


数组旨在保存由整数属性(012 等)表示的有序值序列。

虽然它们是对象,所以你可以将任何你喜欢的属性放在它们上面,但这不是它们的设计目的。

length 旨在计算有序的值序列。它不是对任何名称的每个属性的计数。

【讨论】:

    【解决方案2】:

    数组存储元素。如果你想打电话 person.name="Mr.Brown" 您实际上可以通过以下方式实现它:

    //Initialize the variable
    let person = [];
    
    //Specify the object that will be pushed to the Array 'Person'
    let objectToPush = {name: 'Mr. Brown'};
    
    //Push the object
    person.push(objectToPush);
    
    //Get Length
    console.log(person.length); //<--- Will return 1;
    
    //Call the name property inside the object
    console.log(person[0].name); //<-- returns 'Mr.Brown'
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2016-02-03
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多