gpt4 book ai didi

javascript - 在构造函数中使用循环创建多个对象

转载 作者:行者123 更新时间:2023-12-02 22:44:21 27 4
gpt4 key购买 nike

尝试在构造函数的函数中创建多个对象时遇到问题。

我正在尝试创建多个对象,每个对象都有数组 hand,并且每个对象都有名称 player(x),因此它将是 player0: [array],player1:[array],但它不起作用。我收到错误

Cannot set property '0' of undefined

代码:

function Player () {
this.hand = []
}

function Players () {

}

Players.prototype.createPlayers = function (x) {
for (let i = 0; i < x; i++) {
this.player[i] = new Player()
}
}

let gamer = new Players()
console.log(gamer)

gamer.createPlayers(3)
console.log(gamer.players)

最佳答案

这是可行的尝试一下,这是你想要的吗?

function Player () {
this.hand = []
}

function Players () {
this.player = [];
}

Players.prototype.createPlayers = function (x) {
for (let i = 0; i < x; i++) {
this.player[i] = new Player()
}
}

let gamer = new Players()
console.log(gamer)

gamer.createPlayers(3)
console.log(gamer.players)

关于javascript - 在构造函数中使用循环创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com