数组在变量中显示未定义

时间:2016-09-15 14:27:01

标签: arrays node.js

我已经输入了一个对数据数组执行函数的模块。当我运行该函数时,我得到了我的服务器中的结果,但它们似乎没有存储在我的变量中,而变量未定义。有人可以告诉我为什么当我在服务器中看到数组时,我的数组是否未定义?

 var net = require('net');
 var foo = require('./employeeModule');
 var _ = require('underscore');
 var colors = require('colors/safe');



var server = net.createServer(
  function(socket){
    console.log("Client connection...");

    socket.on('end', function(){
      console.log("Client disconnected...");
    });

//  process data from client
socket.on('data', function(data){
  var command = data.toString();
  var results={};
  console.log("Received Command: " +command);
    if (command == "lookupByLastName Smith")
      {
         function lastName(results)
         {
          var results = foo.lookupByLastName('Smith');
          console.log('These are the results: '+ results)
         }  
      lastName();
      } 

    else if (command == "addEmployee William Smith")
      {
        function addEmp(results)
        {
          var results = foo.addEmployee('William', 'Smith');
          console.log('These are the results: '+ results)
        }
       addEmp();  
       }

    else if (command == "lookupById 4")
      {
        function lookId(results)
        {
          var results = foo.lookupById(4);
          console.log('These are the results: '+ Name)
         }  
      lookId();
      }

    else if (command == "bye")
      client.end();

    else console.log(colors.green("**"+command+" Command not recognized!**"));     

  });     
});


//listent for client connections
 server.listen(1000, function(){
  console.log("Listening for client connections");
 });

1 个答案:

答案 0 :(得分:0)

首先,您的代码有什么问题:

  • var results={}:未使用var results
  • 您有3个功能lastNameaddEmplookId。所有都被调用,没有任何内容被传递,因此results var总是未定义。
  • 在你定义另一个var results的每个函数中,所以,results参数没有任何用处(比如覆盖它)。
  • lookId var Name中未定义。
  • 我认为您的参数是硬编码的(command s,如William Smith4Smith),因为它是某种类型的" test&# 34; /学习练习。我不建议你在回调函数中定义3个函数(因为它们在每次调用回调时都被定义)。

如果你想保持结果这样做(遵循你的编码类型):

function addEmp(){
  var res = foo.addEmployee('William', 'Smith');
  console.log("There asre the results: " + res);
  return res;
}
results = addEmp(); // now you set the value to results

或多或少会做什么,我会做一些事情(小心,我改变了一点编码类型,边界/输入不受控制):

function lastName(surname){
  return foo.lookupByLastName(surname);
}
function addEmp(name, surname){
  return foo.addEmployee(name, surname);
}
// ...

function socketData(data){
  var args = data.toString().split(' '); // assuming space as splitter
  var results;
  var command = args[0];
  switch(command){
  case 'lookupByLastName':
    results = lastName(args[1]);
    break;
  case 'addEmp':
    results = addEmp(args[1], args[2]);
    break;
  default:
    // ...
  }
  // do something with results
}

var server = net.createServer(function(socket){
  // ...
  socket.on('data', socketData);
  // ...
});