簡體   English   中英

類實例的Javascript數組

[英]Javascript Array of Instances of a class

在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 )手動執行此操作; 但我正在尋找一種以某種方式自動執行此操作的方法。 有內置功能嗎? 我應該使用循環嗎?

通過將類更改為以下內容,我找到了在創建新實例時執行此操作的答案:

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

要使用靜態數量的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)));

您可以創建一個類,該類是播放器的容器類。 這將允許容器創建播放器並對其進行管理。 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()) 

到目前為止,我無法評論您的答案,因此有一個補充:

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

請注意:在這幾行中有很多糟糕的做法,您不應將構造函數綁定到可能在其他地方初始化或未初始化的變量,而將構造函數與任何外部糟糕的事物混為一談。 同樣,類通常以標題區分大小寫。

另外,確實可以在維護引用的同時更改consts屬性,因此可以將對象推送到聲明為const的數組中,但它實際上不會合計為自說明代碼,因此,如果您要修改此數組,只需從一開始就用“ let”聲明它。

您可以在類中使用變量(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