gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:46:36 24 4
gpt4 key购买 nike

我想要实现的是:

  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

我们会考虑并感谢任何帮助。如果我需要澄清任何事情,请告诉我。

最佳答案

在构造函数中更新此行

allProjects.push(this);

我测试了它,它按照你的预期工作。

关于javascript - 在 JavaScript 中从数组中的对象访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51903741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com