简体   繁体   English

类实例的Javascript数组

[英]Javascript Array of Instances of a class

In JS, I have a class called player which is: 在JS中,我有一个名为player的类,该类是:

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

and I have two instances of it, called PL1 and PL2 : 我有两个实例,分别称为PL1PL2

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

I also have an array called PLAYERS : 我也有一个名为PLAYERS的数组:

let PLAYRES = [];

now, the question is how can I create an array with all of the instances of the class player ? 现在,问题是如何用类player所有实例创建一个数组?

I know I can manually do this with PLAYERS.push(PL n ) ; 我知道我可以使用PLAYERS.push(PL n )手动执行此操作; but I'm looking for a way to do this somehow automatically. 但我正在寻找一种以某种方式自动执行此操作的方法。 Is there a built-in function? 有内置功能吗? Should I use a loop? 我应该使用循环吗?

I found an answer for doing this when creating a new instance by changing my class to: 通过将类更改为以下内容,我找到了在创建新实例时执行此操作的答案:

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

To initialize an Array with a static amount of Player objects, you could call new Player() in the array: 要使用静态数量的Player对象初始化数组,可以在数组中调用new Player()

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

You could also dynamically create your player list using a loop: 您还可以使用循环动态创建播放器列表:

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

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. Players类可以公开一个界面,从而可以轻松地单独或整体与玩家进行交互。 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()) 

I can't comment your answer as of now so here's an addition: 到目前为止,我无法评论您的答案,因此有一个补充:

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

PLEASE: be aware there's a whole lot of awful practices in this few lines, you shouldn't tie a constructor to a variable that may or may not be initialized somewhere else, meddling with the constructor with whatever external is plain awful. 请注意:在这几行中有很多糟糕的做法,您不应将构造函数绑定到可能在其他地方初始化或未初始化的变量,而将构造函数与任何外部糟糕的事物混为一谈。 Also classes are usually title-cased. 同样,类通常以标题区分大小写。

Plus as a side note, while it's real that you can change consts properties while maintaining the reference, so you can push objects in an array that's declared as const, it really doesn't add up as self-documenting code, so, if you are going to modify this array, just declare it with "let" from the start. 另外,确实可以在维护引用的同时更改consts属性,因此可以将对象推送到声明为const的数组中,但它实际上不会合计为自说明代码,因此,如果您要修改此数组,只需从一开始就用“ let”声明它。

You can use a variable (objectArrays) with the class: 您可以在类中使用变量(objectArrays):

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

}
objectArrays = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM