2016-07-30 54 views
-1

我有两个阵列,一个与数据如何使用数据数组和for循环来实例化对象?

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将具有值:标题: “1”,上载: “一”,秒:1

a2的值:标题:“2”,上传者:“b”,秒数:2

一样的休息。

或者也许是有其他方式来完成下面的任务?

使用数组数组和for循环来实例化5个视频对象。

+1

哪个任务?我不清楚这个问题...... – Rayon

+1

你是什么意思的“对象的名称”?对象没有名字。他们可以被保存在一个变量,或一个数组,或另一个对象... – 2016-07-30 19:52:15

+0

我需要使用数据数组和循环来创建5类实例。 – Cerber

回答

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);