我有一个构造函数,用于将新数据推送到数组(在本例中为 allEntries
)
function entry (title, info) {
this.title = title;
this.info = [ { name : info } ];
}
var allEntries = []
我正在尝试弄清楚如何为 this.info
传递多个对象,例如:
allEntries.push( new entry( 'title one', ['info 1', 'info 2'] ) );
为了获得类似的东西:
{
title: 'title one',
info : [
{ name: 'info 1'},
{ name: 'info 2'}
]
}
我该怎么做?
最佳答案
传递一个数组并迭代它以使用 Array.prototype.forEach 添加所有项目.
function entry (title, info) {
this.title = title;
this.info = [];
info.forEach(function (infoItem) {
this.info.push({ name : infoItem});
}, this);
}
这样调用它:
var myEntry = new entry('foobar', ['info1', 'info2']);
顺便说一句:通常,类的名称前面有一个大写字母,以便能够将它们与函数(总是小写)区分开来,因此您可能想将其命名为“Entry”。
关于javascript - 将多个对象传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565147/