如何解决当我制作一个新类时,试图将数据推送到一个空数组,无法按预期工作
因此,我尝试将实例化的竞争者对象的值推入一个空数组,如在ManageContestant类内的SubmitForm函数中所见。我将数组记录到控制台以查看是否存在任何当前值,但似乎这只是一个没有值的参赛者对象的空实例。当我的代码是分开的而不是放在我创建的新创建的ManageContestant类中时,它最初可以工作。
但是,我进行了此更改,因为我读到不建议您练习在全局空间中创建变量?而且这似乎对我来说不合适,所以我宁愿选择ManageContestant类中的空数组,或者如果有人建议创建更好的代码,还有其他建议。我将提供不带ManageContestant类的有效代码以及非有效代码。
控制台值:
Sucessfully pushing contestants in the array
No object data showing when I click the arrow using the ManageContestant class
工作代码没有ManageContestant类
class Contestant {
constructor(name,age,location,song,link){
this.name = name;
this.age = age;
this.location = location;
this.song = song;
this.link = link;
}
}
const contestantDataArray =[];
document.querySelector(".regoForm").addEventListener('submit',function(e){
// Instantiate Contestant - create an instance
// Get values from contestant rego form
const name = document.querySelector("#contName").value,age = document.querySelector("#contAge").value,location = document.querySelector("#contLocation").value,song = document.querySelector("#song").value,link = document.querySelector("#link").value;
const contestant = new Contestant(name,link);
contestantDataArray.push(contestant);
Store.addContestant(contestant);
}
e.preventDefault();
});
使用ManageContestant类修复的代码
class Contestant {
constructor(name,link){
this.name = name;
this.age = age;
this.location = location;
this.song = song;
this.link = link;
}
}
class ManageContestant{
constructor(){
// pass the data in the profileIterator function
this.contestantDataArray = [];
this.events();
}
//Events
events() {
// Create event for next button
document.querySelector(".regoForm").addEventListener('submit',() => this.submitForm())
}
//Methods
submitForm(){
let array = this.contestantDataArray;
// Add contestant to list
ui.addContestantToList(contestant);
// THE PROBLEM IS HERE,THE ARRAY IS NOT GETTIN ANY VALUES OF THE CONTESTANT OBJECT BEING PUSHED
array.push(contestant);
Store.addContestant(contestant);
};
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。