我正在使用 socket.io 创建一个 Node.js 聊天
问题是,当我看到 history
的 console.log
时,我看到一个包含大量空值的数组,最后是我的历史条目
[null,null,null ......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]
数组中怎么会有这些null?
这是我的代码的一部分。
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,[]]
最佳答案
如果您有一个空数组并用一个大数字(例如您的房间 ID)对其进行索引,则该数组中该数字之前的所有槽都将填充 undefined
(转换为 null
在 JSON 中)。
所以试着把历史变成一个对象:
var history = {};
关于arrays - NodeJS - 创建空数组会导致数组中有很多空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15547847/