使用typeof后node.js变量未定义错误

时间:2013-12-06 10:29:56

标签: node.js socket.io

这是我的代码

   if((typeof session) !== undefined && (typeof session.username) !== undefined){
        data = session.username+" online";  
        io.sockets.emit('update_common_message',data);

        socketsOfClients[session.username].push(socket.id);
    }

我收到错误

    TypeError: Cannot read property 'username' of undefined

我不知道我的代码有什么问题......

3 个答案:

答案 0 :(得分:2)

typeof返回一个字符串,因此您还需要对字符串进行测试:

if ((typeof session) !== 'undefined' ...)

答案 1 :(得分:1)

我认为,这就足够了,看起来也更清洁。

if (session && session.username) {
  data = session.username + " online";
  io.sockets.emit('update_common_message', data);

  socketsOfClients[session.username].push(socket.id);
}

答案 2 :(得分:1)

您的问题是typeof返回一个字符串:

if((typeof session) !== 'undefined' && (typeof session.username) !== 'undefined'){
    // ...
}