我创建使用socket.io
的问题Node.js的聊天的是,当我看到的history
的console.log
我看到一个数组与空了很多并在结束我的历史记录 [null,null,null......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]
的NodeJS - 创建数组空数组结果有很多空的
这些空值是如何来到阵列中?
这是我的代码的一部分。
var history = [];
io.sockets.on('connection', function (socket) {
socket.on('send', function (message) {
var date = time();
io.sockets.in(socket.room).emit('message', socket.username, message, date);
history[socket.room].push({ username: socket.username, message: message, date: date });
console.log(history);
});
socket.on('joinroom', function (room, username) {
socket.room = room;
socket.join(room);
if (typeof history[room] === 'undefined')
history[room] = [];
});
});
编辑更多细节:
创建用于每个房间的空数组时的问题是在“joinroom”事件。
这里是我做了一些测试:
socket.on('joinroom', function (room, username) {
socket.room = room;
socket.join(room);
console.log(typeof history[room] == 'undefined');
history[room] = [];
console.log(typeof history[room] == 'undefined');
console.log(JSON.stringify(history));
});
控制台日志:
true false [null,null,null,null,..................,null,[]]
我想你想'history'是一个对象而不是数组:'VAR历史= {};' – robertklep 2013-03-21 14:25:49
然后我要去怎么加每个房间的历史记录? '.push()'仅被Array支持。 – 2013-03-21 14:27:21
你不是直接推到'history',而是在*'history'中的数组*上,这样就可以工作得很好。 – robertklep 2013-03-21 14:29:18