NodeJS - Creating empty array results in array wit

2019-07-19 04:21发布

I am creating a Node.js chat using socket.io
The problem is that when I see the console.log of history I see an array with A LOT of nulls and at the end my history entries [null,null,null......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]

How come these nulls are in the array?
Here is a part of my code.

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] = [];

    });

});

Edit for more details:

The problem is in the 'joinroom' event when creating the empty array for each room.
Here are few tests that I've made:

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));
});

The console logs:

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

2条回答
我命由我不由天
2楼-- · 2019-07-19 04:46

try below code changing to 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);

});
查看更多
Emotional °昔
3楼-- · 2019-07-19 05:00

If you have an empty array and index it with a large number (like your room id's), all slots in the array before that number are filled with undefined (which translates to null in JSON).

So try making history an object instead:

var history = {};
查看更多
登录 后发表回答