NodeJS-创建空数组会导致数组中包含大量空值 [英] NodeJS - Creating empty array results in array with a lot of nulls

查看:110
本文介绍了NodeJS-创建空数组会导致数组中包含大量空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用socket.io创建Node.js聊天。

问题是当我看到<$ c $的 console.log 时$ c> history 我看到一个带有很多空值的数组,最后我的历史记录条目
[null,null,null ... [ {用户名:'Nobody Example',消息:'231',日期:'03 / 21/2013 14:23:58'}]]

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:

问题是在为每个房间创建空数组时的'joinroom'事件中。

这是我进行的一些测试:

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

控制台日志:

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


推荐答案

如果您有一个空数组,并使用大量数字(例如您的房间ID)对其进行索引,则该数字之前的所有插槽充满 undefined (在JSON中转换为 null )。

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

这篇关于NodeJS-创建空数组会导致数组中包含大量空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆