【问题标题】:How to generate a new var that contains an object by clicking on a button?如何通过单击按钮生成包含对象的新变量?
【发布时间】:2019-05-03 23:49:00
【问题描述】:

所以我要做的是在每次填写表格并单击相应按钮时创建一个包含球队信息(名称、联赛、球员)的新对象。

团队对象是类团队的一个实例。我目前正在努力将生成的团队存储为变量。

不幸的是,每次单击按钮时都会覆盖该变量。

我该如何解决这个问题?每次单击按钮时,我能否以某种方式创建一个动态变量名称(例如 var name = team.name)?我想要为每个创建的团队创建一个新变量,以便我始终可以识别和访问它。

对不起,我还是个 JS 新手。干杯! :)

class team {
    constructor(teamname, teamleague, players) {
        this.teamname = teamname;
        this.teamleague = teamleague;
        this.players = [];

    }

var generatedTeamName = "";
var generatedTeamLeague = "";
var newteam = "";

var listofTeams =[];

$(document).ready(function(){
/* --- NEW TEAM ----------------------------------------------------------------------------------------------------*/

    $("#generateteam").click(function(){
      generatedTeamName = $('input[name="text-5"]').val();
      generatedTeamLeague = $('input[name="text-6"]').val();

      var storenewTeamhere = new team (generatedTeamName, generatedTeamLeague, []); 

    })
});

}

【问题讨论】:

  • 不,不要尝试使用动态变量名。您真正想要的是存储团队对象的集合,例如作为一个数组。看起来您甚至已经创建了该数组。

标签: javascript class object var


【解决方案1】:

我不确定您希望如何使用存储的团队数据,但有很多方法可以做到这一点。

class Team {
  constructor(teamname, teamleague, players) {
    this.teamname = teamname;
    this.teamleague = teamleague;
    this.players = players;
  }
}

/* the array method */
const listOfTeams = [];

$("#generateteam").click(function () {
  let name = $('input[name="text-5"]').val();
  let league = $('input[name="text-6"]').val();
  let team = new Team(
    name,
    league,
    []
  );

  listOfTeams.push(team);

  // you can access the team as simply `team` here
});

// here you can access the teams by array index
// listOfTeams[i]

/* the object method */
const teams = {};

$("#generateteam").click(function () {
  let name = $('input[name="text-5"]').val();
  let league = $('input[name="text-6"]').val();
  let team = new Team(
    name,
    league,
    []
  );

  teams[name] = team;

  // you can access the team as simply `team` here
});

// you can now access the team by teamname
// teams['Some Team Name']

【讨论】:

  • 您好,感谢您的快速回复。无论哪种情况,我现在如何访问我的团队,例如更改或添加变量(如玩家)?我想我在掌握对象和类的概念方面仍然有些挣扎。干杯!
  • 如果您使用第二种方法,即将它们存储在一个对象中,您可以通过teams['Some Team Name'].players 访问players 数组,您可以通过teams['Some Team Name'].players.push(player) 添加玩家。此外,有很多博客很好地解释了 javascript 中的对象和数组,您应该尝试阅读它们。其次,如果你有任何编程经验,那么 JS 对象大致类似于 Python 中的 dicts 和 Java 中的 HashMaps。如果你不这样做,那么在线做一个基本的交互式教程应该会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多