套接字 io:无法在 socket.rooms 上循环或使用数组方法

Socket io: Cannot for loop or use array methods on socket.rooms

我要写:

socket.on("create-room", (roomID)=> socket.room = roomID)

let userS_selected_room = 'f2eac135-eafd-49e1-adc7-c89351703896';

for(room in socket.rooms){
  if(room === userS_selected_room) {do_stuff()}
}

我不明白这些:Map(4)、[Set]

console.log(socket.rooms)

Set(4) {
  'zBROv1Lug0XhoQxCAAAB',
  'room1',
  '9e9ecaa6-473a-43a6-9ab7-60ff034ab614',
  '1dc1547c-d265-4d5a-bd3f-9a5d37bf883a'
}

console.log(插座)/

...
    rooms: Map(4) {
      '6Otk--hk5SHOVRcrAAAD' => [Set], //socket id 
      'room1' => [Set],
      'f2eac135-eafd-49e1-adc7-c89351703896' => [Set], //this is room id
      '91fdf074-a1e7-493b-97b9-5a6050095697' => [Set] //this is room id
    },
...

该输出告诉您 socket.roomsMap object, which maps keys (like '6Otk--hk5SHOVRcrAAAD') to Set objects. You can loop through the map using for-of(不是 for-in):

for (const [roomid, room] of sockets.rooms) {
    // ...here, `roomid` will be the ID of the room, and
    // `room` will be a `Set`...
}

如果您不需要房间 ID,可以使用 values 方法并循环其结果:

for (const room] of sockets.rooms.values()) {
    // ...here, `room` will be a `Set`...
}

或者,如果您有房间 ID,请通过 get 获取该房间的 Set:

const room = socket.rooms.get(roomID);

您必须参考您用来填充 socket.rooms 的任何库才能找出 Set 对象包含的内容,但要遍历集合中的元素,你会再次使用 for-of

for (const whatever of room) {
    // ...use `whatever`...
}