NodeJS - 创建空数组导致数组中包含大量空值

Iva*_*kov 2 arrays node.js socket.io

我创建使用socket.io一个Node.js的聊天
的问题是,当我看到console.loghistory我看到空了很多,并在年底我的历史记录条目的数组 [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] = [];

    });

});
Run Code Online (Sandbox Code Playgroud)

编辑更多详细信息:

在为每个房间创建空数组时,问题出在'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));
});
Run Code Online (Sandbox Code Playgroud)

控制台日志:

true
false
[null,null,null,null,..................,null,[]]

rob*_*lep 5

如果您有一个空数组并使用大数字(如房间ID)对其进行索引,那么该数字前面的数组中的所有插槽都将被填充undefined(转换为nullJSON格式).

因此,尝试将历史作为对象:

var history = {};
Run Code Online (Sandbox Code Playgroud)