You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js:如何避免使用已存在的userID创建Game类实例

解决方案:用类静态属性管理已创建实例的ID

直接遍历已创建的对象既麻烦又低效,更合理的方式是用类的静态属性来存储已使用的userID,这样在构造函数里就能快速完成检查。

推荐实现:用Map存储(支持后续获取实例)

class Game {
    // 静态Map:key是userID,value是对应的Game实例
    static registeredGames = new Map();

    constructor(userID) {
        if (Game.registeredGames.has(userID)) {
            console.log("Game with this ID already exists");
            return; // 终止实例创建流程
        }

        this.gameID = userID;
        Game.registeredGames.set(userID, this);
        console.log("Created Game");
    }

    // 可选:添加销毁方法,移除已注册的ID
    destroy() {
        Game.registeredGames.delete(this.gameID);
        console.log("Game destroyed");
    }
}

// 测试
const gameOne = new Game(1234);   // "Created Game"
const gameTwo = new Game(1234);   // "Game with this ID already exists"
const gameThree = new Game(1235); // "Created Game"

gameOne.destroy();
const gameFour = new Game(1234); // "Created Game"

简化版:用Set只存ID

如果不需要关联实例,仅需检查ID是否存在,用Set更轻量化:

class Game {
    static usedIDs = new Set();

    constructor(userID) {
        if (Game.usedIDs.has(userID)) {
            console.log("Game with this ID already exists");
            return;
        }

        this.gameID = userID;
        Game.usedIDs.add(userID);
        console.log("Created Game");
    }

    destroy() {
        Game.usedIDs.delete(this.gameID);
    }
}

为什么不用数组?

数组的includes方法是O(n)复杂度,当实例数量多的时候,检查速度会变慢;而Map/Set的has方法是O(1),效率高得多,而且后续的添加、删除操作也更便捷。

内容的提问来源于stack exchange,提问作者sofabeddd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:40:24