如何根据用户输入多次实例化 class?

How to instantiate a class multiple times based on a user input?

我正在尝试创建一个棋盘游戏,并想根据用户提供的次数实例化 class 人类。显然,我正在尝试为每个对象分配不同的 ID,但为了实例化玩家数量,以下循环不起作用:

var question = prompt('how many players');
var numOfPlayers = parseInt(question);

class Human {
  constructor (id) {
    this.id = id;
    this.health = 100;
    this.hammer = false
    this.knife = false;
    this.sword = false;
    this.baseballbat = false;
    this.damage = 0;
    this.location = {
      x: Math.floor(Math.random() * 8),
      y: Math.floor(Math.random() * 8)
    }
  }

  moveTo(x, y){
    this.location.x += x;
    this.location.y += y;
  }
}

var i;
for (i = 0; i < numOfPlayers; i++) {
    const player = new Human(id = i);
}

首先,我希望我已经理解了您在这里想要实现的目标。 "const player" 的范围限制在循环内。如果您希望能够在循环外访问它,您需要同样声明一个 list/array。

同样的代码可能是这样的:

var players = [];
for(let i = 0; i < numOfPlayers; i++) {
    players.push(new Human(i));
}

注意:如果您不想在循环外使用变量 'i',您可以使用 'let' 关键字在 'for' 内声明它,如下所示在上面的代码中。

class Human {
    constructor (id){
        this.id = id;
        this.health = 100;
        this.hammer = false
        this.knife = false;
        this.sword = false;
        this.baseballbat = false;
        this.damage = 0;
        this.location = {
            x:Math.floor(Math.random()*8),
            y:Math.floor(Math.random()*8)
        }

        console.log(`Human created with id of ${id}`); //Remove this just to show you that your class is being instantiated for each 'player'
    }

    moveTo(x,y){
        this.location.x += x;
        this.location.y += y;
    }
}

let numOfPlayers = prompt('How many players?');

const _init = () => {
    if(parseInt(numOfPlayers) > 0) {
        for (let i = 0; i < numOfPlayers; i++) {
            new Human(i)
        }
    }
}

_init();