NodeJSdynamic复制数组

人,有没有办法让以下块dynamic,基于主机和端口arrays的长度? 要么使用underscore.each,要么类似的东西?

var hosts = ['ip1','ip2','ip3]; var ports = ['port1','port2','port3']; this.replSet = new ReplSetServers([ new Server(this.hosts[0], this.ports[0]), new Server(this.hosts[1], this.ports[1]), new Server(this.hosts[2], this.ports[2]) ]); 

谢谢!

我已经试过没有用:

 this.servers = []; _.each(this.hosts, function (this.host) { this.servers.push(new Server(this.hosts[0], this.ports[0])); }); 

谢谢!

语法错误, _.eachcallback的第一个参数是当前元素,第二个参数是索引。 您可以遍历其中一个数组,并使用index来select第二个数组中的相应元素:

 _.each(hosts, function (element, index) { this.servers.push(new Server(element, ports[index])); }); 

你也可以使用_.map方法:

 this.servers = _.map(hosts, function (element, index) { return new Server(element, ports[index]); }); 

你在每个循环中都有一个错误。 你总是使用主机[0]。

 var hosts = ['ip1','ip2','ip3]; var ports = ['port1','port2','port3']; this.servers = []; _.each(hosts, function (host,index) { this.servers.push(new Server(host, ports[index])); }); this.replSet = new ReplSetServers(this.servers); 

另外你可以使用_.map:

 var hosts = ['ip1','ip2','ip3]; var ports = ['port1','port2','port3']; this.servers = _.map(hosts, function (host,index) { return new Server(host, ports[index]); }); this.replSet = new ReplSetServers(this.servers); 

这工作:

 var servers = []; _.each(hosts, function (host, index) { servers.push(new Server(host , ports[index])); }); this.replSet = new ReplSetServers(servers); 

多谢你们!