从JavaScript数组中的对象访问变量?

时间:2018-08-17 22:54:28

标签: javascript

我想要实现的是:

  1. 声明一个将容纳所有项目的数组。
  2. 构造函数创建一个将成为新项目的对象。然后,构造函数立即将其推入allProject数组。
  3. 然后,我想在对象._hours已在数组中之后显示其中的某些变量。

我的代码包括:

//Declare Array that will Host Projects
const allProjects = [];

//Create Parent Class that creates objects (Project)
class Project {

constructor(projTitle, projDescription, projHours) {

    //Declare variables
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;

    //Send newly constructed object directly to next space in array.
    allProjects.push(constructor(projTitle, projDescription, projHours));

    }
}

//Create new object.
const DataEntry = new Project('Data Entry', 'Enter Data into Amazon', '4 Hours');

//Display the name variable housed in the object that was pushed into allProjects array.
console.log(allProjects[0].DataEntry._name);

输出看起来像这样:

/Users/ervin/WebstormProjects/untitled/Project Management.js:30
console.log(allProjects[0].DataEntry._name);
                                 ^

TypeError: Cannot read property '_name' of undefined
    at Object.<anonymous> (/Users/ervin/WebstormProjects/untitled/Project 
Management.js:30:38)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

Process finished with exit code 1

任何帮助都被考虑和赞赏。让我知道是否需要澄清任何事情。

2 个答案:

答案 0 :(得分:1)

您可以像这样访问._nameallProjects[0]._name

但是您实际上是在推错方向。调用new Project(...)后,您将收到参数,因此按如下所示进行推送:

//Declare Array that will Host Projects
const allProjects = [];

class Project {
  constructor(projTitle, projDescription, projHours) {
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
  }
}

//Create new object.
const DataEntry = new Project('Data Entry', 'Enter Data into Amazon', '4 Hours');
allProjects.push(DataEntry)

//Display the name variable housed in the object that was pushed into allProjects array.
console.log(allProjects[0]._name)

完全没有经过测试,但是应该可以使用!

答案 1 :(得分:1)

在构造函数中更新此行

  

allProjects.push(this);

我已经对其进行了测试,它可以按预期工作。