私は socket.io を使用して Node.js チャットを作成し
てconsole.log
いhistory
ます
[null,null,null......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]
これらのヌルが配列にあるのはなぜですか?
これが私のコードの一部です。
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));
});
コンソール ログ:
真実 間違い [ヌル、ヌル、ヌル、ヌル、……、ヌル、[]]