我的班级看起来像这样:
const fs = require('fs');
let stream = fs.createReadStream('file.txt', 'utf8');
let transform = new Delimited(/\n\n(?=Part #\d)/g);
let array = [];
transform.on('data', (chunk) => array.push(chunk));
transform.on('end', () => console.log(array));
stream.pipe(transform);
我正在尝试创建一个对象数组,但我只能创建一个。 有人能说出我做错了吗?
我创建这样的数组:
var Coin = {
_id: null,
createGame: function(id) {
this._id = id;
},
start: function() {
}
};
最后我想拥有带对象的数组,例如我将获取数组的第一个数组,并从Coin类执行其他方法。
答案 0 :(得分:2)
您需要将新创建的项目推送到数组,如下所示:
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);

<强>更新强>
最后我希望有一个带对象的数组,例如我会 取第一个数组,并从Coin类中执行其他方法。
为了这个目的,如果我是你,我会创建一个带有键的对象,其中id和值引用Coin
个对象:
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();
&#13;
答案 1 :(得分:0)
class Coin {
constructor(id) {
this._id = id;
}
start() {
console.log('starting');
}
}
CoinArray = [];
CoinArray['123'] = new Coin(123);
CoinArray['333'] = new Coin(333);
CoinArray['123'].start();
我还建议以这种方式管理id:
let id = 0;
class Coin {
constructor() {
this._id = id++;
}
start() {
console.log('starting');
}
}
CoinArray = [];
CoinArray.push(new Coin());
CoinArray.push(new Coin());
CoinArray[0].start();