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

Arrays NodeJS-创建空数组会导致数组中包含大量空值,arrays,node.js,socket.io,Arrays,Node.js,Socket.io,我正在使用socket.io创建Node.js聊天室 问题是,当我看到history的console.log时,我看到一个包含大量空值的数组,并且在我的历史记录条目的末尾 [null,null,null……[{用户名:“Nobody-Example”,消息:“231”,日期:“03/21/2013 14:23:58”}] 为什么这些空值会出现在数组中? 这是我代码的一部分 var history = []; io.sockets.on('connection', function (socke

我正在使用socket.io创建Node.js聊天室
问题是,当我看到
history
console.log
时,我看到一个包含大量空值的数组,并且在我的历史记录条目的末尾
[null,null,null……[{用户名:“Nobody-Example”,消息:“231”,日期:“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));
});
控制台记录:

true false [null,null,null,null,..................,null,[]] 真的 假的
[null,null,null,null,…..,null,[]尝试下面的代码更改为对象(哈希)


如果您有一个空数组,并使用一个大的数字(如房间id)对其进行索引,则该数字之前的数组中的所有插槽都将填充
未定义的
(在JSON中转换为
null

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

var history = {};

我想你希望
history
成为一个对象而不是数组:
var-history={}那么如何为每个房间添加历史记录条目
.push()
仅受数组支持。您不是直接推到
历史记录上,而是推到
历史记录中的数组上,这样就可以正常工作。当我更改
历史记录={}
时,实际上没有任何更改。空值仍然存在。我认为node.js确实有些问题,因为我在浏览器控制台中测试了我的代码(因为这只是对数组和对象的简单操作),然后得到了正确的结果(数组没有空值)。这些空值是索引具有大值的数组的一个明显标志:
var a=[];a[23]=1;log(JSON.stringify(a))这是错误的,因为它只保留每个房间的最后一个条目
history[socket.room]=
必须是array.Ooook,它在JSON中被翻译成
null
,这就是我为什么来到这里的原因。谢谢
var history = {};