类实例的Javascript数组

时间:2018-09-18 00:31:42

标签: javascript class object

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

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

,我有两个实例,分别叫PL1PL2

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

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

let PLAYRES = [];

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

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

5 个答案:

答案 0 :(得分:1)

通过将类更改为以下内容,我找到了创建新实例时执行此操作的答案:

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

答案 1 :(得分:1)

要使用静态Player个对象初始化一个数组,可以在数组中调用new Player()

const players = [new Player('name1'), new Player('name2'), new Player('name3')];

您还可以使用循环动态创建播放器列表:

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

答案 2 :(得分:1)

您可以创建一个类,它是玩家的容器类。这将允许容器创建播放器并对其进行管理。 Players类可以公开一个界面,从而可以轻松地单独或整体与播放器进行交互。这样的事情可能是一个好的开始,并且可能会添加更多的功能或不同的组织:

// 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())

答案 3 :(得分:0)

到目前为止,我无法评论您的回答,因此有一个补充:

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

请:请注意,在这几行中有很多糟糕的做法,您不应将构造函数与可能在其他地方初始化或未初始化的变量联系在一起,而将构造函数与任何外部可怕的事物混为一谈。同样,类通常也以标题大小写。

此外,确实可以在维护引用的同时更改consts属性,因此您可以 将对象推入声明为const的数组中,但实际上并不会累加作为自记录代码,因此,如果要修改此数组,只需从头开始用“ let”声明它。

答案 4 :(得分:0)

您可以在类中使用变量(objectArrays)

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

}
objectArrays = [];