NodeJS - Creating empty array results in array with a lot of nulls

我与影子孤独终老i 提交于 2020-01-04 15:59:07

问题


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,[]]

回答1:


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 = {};



回答2:


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

});


来源:https://stackoverflow.com/questions/15547847/nodejs-creating-empty-array-results-in-array-with-a-lot-of-nulls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!