我的类(class)是这样的:
var Coin = {
_id: null,
createGame: function(id) {
this._id = id;
},
start: function() {
}
};
我正在尝试创建一组对象,但我只能创建一个。 有人能告诉我做错了什么吗?
我这样创建数组:
CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start
最后我想要一个带有对象的数组,例如我将获取数组的第一个 el,并执行 Coin 类中的其他方法。
最佳答案
您需要将新创建的项推送到您的数组,如下所示:
CoinArray.push(new Coin.Create('123));
另一方面,如果你想创建一个对象,其键 id 和值对应于 Coin 对象,你应该试试这个:
CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');
注意:
如果你想将它用作 constructor function,我认为你应该重构一下 Coin
:
function Coin(id){
this.id = id;
}
进行此更改后,您可以按如下方式使用它:
CoinArray.push(new Coin('123'));
function Coin(id){
this.id = id;
}
var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));
console.log(CoinArray);
更新
At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.
为了这个目的,如果我是你,我会创建一个对象,其中包含对 Coin
对象的 ids 和 values 引用的键:
function Coin(id){
this.id = id;
}
Coin.prototype.start = function(){
console.log("game with id "+this.id+" started.");
}
Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');
Coins['456'].start();
关于javascript - 如何在 node.js 中创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931500/