gpt4 book ai didi

一个类的实例的Javascript数组

转载 作者:行者123 更新时间:2023-11-29 18:48:18 25 4
gpt4 key购买 nike

在 JS 中,我有一个名为 player 的类,它是:

class player {
constructor(name) {
this.name = name;
}
}

我有它的两个实例,称为 PL1PL2:

const PL1 = new player ('pl1name');
const PL2 = new player ('pl2name');

我还有一个名为 PLAYERS 的数组:

let PLAYERS = [];

现在,问题是如何创建一个包含类 player 的所有实例的数组?

我知道我可以使用 PLAYERS.push(PLn) 手动执行此操作;但我正在寻找一种以某种方式自动执行此操作的方法。有内置函数吗?我应该使用循环吗?

最佳答案

您可以创建一个类作为玩家的容器类。这将允许容器创建玩家并管理他们。 Players 类可以公开一个接口(interface),从而可以轻松地与玩家单独或作为一个整体进行交互。像这样的东西可能是一个好的开始,可以用更多的功能或不同的组织来填充:

// An individual player. Holds properties and behavior for one player
class Player {
constructor(name) {
this.name = name;
}
play() {
console.log(this.name, "plays")
}
}

// Class that holds a collection of players and properties and functions for the group
class Players {
constructor(){
this.players = []
}
// create a new player and save it in the collection
newPlayer(name){
let p = new Player(name)
this.players.push(p)
return p
}
get allPlayers(){
return this.players
}
// this could include summary stats like average score, etc. For simplicy, just the count for now
get numberOfPlayers(){
return this.players.length
}
}

let league = new Players()
league.newPlayer("Mark")
league.newPlayer("Roger")

// list all the players
console.log(league.numberOfPlayers + " Players)
console.log(league.allPlayers)


// make them do something
league.allPlayers.forEach(player => player.play())

关于一个类的实例的Javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377344/

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