将数据推送到数组时没有对象实例

问题描述

因此,我尝试将实例化的竞争者对象的值推入一个空数组,如在ManageContestant类内的SubmitForm函数中所见。我将数组记录到控制台以查看是否存在任何当前值,但似乎这只是一个没有值的参赛者对象的空实例。当我的代码是分开的而不是放在我创建的新创建的ManageContestant类中时,它最初可以工作。

但是,我进行了此更改,因为我读到不建议您练习在全局空间中创建变量?而且这似乎对我来说不合适,所以我宁愿选择ManageContestant类中的空数组,或者如果有人建议创建更好的代码,还有其他建议。我将提供不带ManageContestant类的有效代码以及不正常的代码

登录到控制台:

Sucessfully pushing contestants in the array

no object data showing when i click the arrow

工作代码没有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
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);
 
 array.push(contestant);
 
 
 Store.addContestant(contestant);
 
     
 };
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)