我正在使用socket.io来创建Node.js聊天
问题是,当我看到console.log
的{{1}}时,我看到一个包含大量空值的数组,最后是我的历史记录条目
history
为什么这些空值在数组中?
这是我的代码的一部分。
[null,null,null......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]
编辑以获取更多详细信息:
在为每个房间创建空数组时,问题出在'joinroom'事件中 以下是我做过的一些测试:
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] = [];
});
});
控制台记录:
true false [null,null,null,null,..................,null,[]]
答案 0 :(得分:5)
如果您有一个空数组并使用大数字(如房间ID)对其进行索引,则该数字前面的数组中的所有插槽都会填充undefined
(在JSON中转换为null
)。
因此,请尝试将历史作为对象:
var history = {};
答案 1 :(得分:0)
尝试下面的代码更改为object(hash);
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);
if(history[socket.room] !== undefined) {
history[socket.room].push = { username: socket.username, message: message, date: date };
} else {
history[socket.room] = [{ username: socket.username, message: message, date: date }];
}
console.log(history);
});