NodeJS动态复制数组

时间:2014-08-23 00:05:54

标签: node.js

伙计们,有没有办法根据主机和端口数组的长度使以下块动态化?是使用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]));
});

谢谢!

3 个答案:

答案 0 :(得分:1)

语法错误,_.each回调的第一个参数是当前元素,第二个参数是索引。您可以迭代其中一个数组并使用index选择第二个数组中的相应元素:

_.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]);
});

答案 1 :(得分:1)

每个循环中都有错误;你总是使用主机[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);

答案 2 :(得分:0)

这有效:

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

谢谢大家!