简体   繁体   English

如何将 obj[key] 分配给数组

[英]how to assign obj[key] to an array

I am trying to assign an empty obj with a variable [key] to an array and push the item to the array but for some reason it doesnt work properly.我正在尝试将带有变量 [key] 的空 obj 分配给数组并将项目推送到数组,但由于某种原因它无法正常工作。 I wonder why the first item in the array is an empty string?我想知道为什么数组中的第一项是空字符串? How to correctly assign it to an array.如何正确地将其分配给数组。 Could any please advice?可以请任何建议吗? thank you!谢谢你!

let online = {};
let users = [];
let userInRoom =[];


 socket.on('join', ({ username, room, uUID }, cb) => {


    if(room in online){
        if(!online[room].includes(username)){
            online[room].push(username);
        }

    }else{
        online[room]=[...userInRoom, username];
    }

    console.log("online", online, "users", users);
   //---> the console result ==> online { general: [ '', 'jiojoij' ] } users [ 'jiojoij' ]

 });

I wonder why the first item in the array is an empty string?我想知道为什么数组中的第一项是空字符串? How to correctly assign it to an array.如何正确地将其分配给数组。

Your logic seems a little confusing.你的逻辑似乎有点混乱。 What's the point of the userInRoom array if it's always empty?如果userInRoom数组总是空的,它有什么意义? I would try something like:我会尝试类似的东西:

if (!(room in online)) {
    online[room] = [];
}
if (!online[room].includes(username)) {
    online[room].push(username);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM