我在for循环中未定义var

时间:2014-04-17 14:50:15

标签: javascript node.js

//Server Functions
var socketArray = [];
var socketRcon = [];
for (var i = 0; i < serversConfig.serversArray.length; i++) {
    socketArray[i] = new Socket;
    socketArray[i].setEncoding("utf8");
    socketArray[i].setNoDelay();
    socketArray[i].setTimeout(1000);
    socketArray[i].connect(serversConfig.serversArray[i].port, serversConfig.serversArray[i].ip);
    socketRcon[i] = serversConfig.serversArray[i].rcon;
    socketArray[i].on("connect", function() {
        this.write(socketRcon[i] + "\n", "utf8");
        console.log("CONNECTED TO THE SERVER...");
    });
    socketArray[i].on("data", function(data) {
        console.log(data);
    });
    socketArray[i].on("error", function(err) {
        console.log("ERROR:" + err);
    });

    socketArray[i].on("close", function(err) {
        console.log("CLOSED:" + err);
    });
};

这是我现在从配置文件连接到多个服务器的代码,我需要每次套接字连接时,我需要向它发送密码。但'socketRcon [i]'是未定义的,为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:2)

因为在代码运行时,i等于serversConfig.serversArray.length,意味着socketRcon[i]未定义。

锚定你的价值:

for( var i=0; i<l; i++) (function(i) {
    // do stuff here
})(i);

答案 1 :(得分:1)

您也可以这样做:

serversConfig.serversArray.forEach(function(srvconfig) {
  var sock = new Socket();
  sock.setEncoding("utf8");
  sock.setNoDelay();
  sock.setTimeout(1000);

  socketArray.push(sock);
  socketRcon.push(srvconfig.rcon);

  sock.on("connect", function() {
    this.write(srvconfig.rcon + "\n", "utf8");
    console.log("CONNECTED TO THE SERVER...");
  });
  sock.on("data", function(data) {
    console.log(data);
  });
  sock.on("error", function(err) {
    console.log("ERROR:" + err);
  });
  sock.on("close", function(err) {
    console.log("CLOSED:" + err);
  });

  sock.connect(srvconfig.port, srvconfig.ip);
});