我有两个数组,其中一个数据
var elements = [["1","a",1],["2","b",2],["3","c",3],["4","d",4],["5","e",5]];
另一个包含我想使用上述数据创建的对象名称。
var names =["a1","a2","a3","a4","a5"];
这是原型类
var Video = function(title,uploader,seconds){
this.title = title;
this.uploader = uploader;
this.seconds = seconds;
}
我希望得到:
a1将具有值:title:" 1",uploader:" a",seconds:1
带有值的a2:标题:" 2",上传者:" b",秒:2
与休息相同。
或者可能还有其他方法可以完成下面的任务吗?
使用数据数组和for循环实例化5个视频对象。
答案 0 :(得分:0)
function Video(title, uploader, seconds) {
this.title = title;
this.uploader = uploader;
this.seconds = seconds;
}
var elements = [["1","a",1],["2","b",2],["3","c",3],["4","d",4],["5","e",5]];
var names =["a1","a2","a3","a4","a5"];
// create instances
var videos = elements.map(data => new Video(...data));
// add them to hashmap
var result = names.reduce((acc, current, index) => {
acc[current] = videos[index];
return acc;
}, {});
console.log(result);