类的 Javascript 实例数组

Sha*_*iar 4 javascript class object

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

class player {
    constructor(name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个实例,称为PL1PL2

const PL1 = new player ('pl1name');
const PL2 = new player ('pl2name');
Run Code Online (Sandbox Code Playgroud)

我还有一个名为的数组PLAYERS

let PLAYRES = [];
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*yer 7

You could create a class that is a container class for the players. This will allow the container to create players and manage them. The the Players class can expose an interface making it easy to interact with the players individually or as a whole. Something like this might be a good start and could be filled out with more functionality or different orginziation:

// 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())
Run Code Online (Sandbox Code Playgroud)

  • 3年后,我现在理解了JS和你的答案:D 将其标记为已接受! (3认同)

hac*_*ave 5

要使用静态数量的对象初始化数组,您可以在数组中Player调用:new Player()

const players = [new Player('name1'), new Player('name2'), new Player('name3')];
Run Code Online (Sandbox Code Playgroud)

您还可以使用循环动态创建玩家列表:

const playerNames = ['name1', 'name2', 'name3'];
let players = [];
playerNames.forEach((playerName) => players.push(new Player(playerName)));
Run Code Online (Sandbox Code Playgroud)