问题
This is similar to this question. However, I want to add a property to an object but I don't know the name of that property. The scenario is that I have some users connecting to a namespace in my socket.io app
, when a user connects a random socket.id
is generated to be able to differentiate that user from the rest of the users, when the user connects they also send their gender to the server (via socket.emit
), now I want to create an object that keeps track of the users' socket ids and genders.
var users = {}; // create empty object
var specialID = socket.id; // get user's socketid
var gender; // suppose gender contains their gender (male or female)
now I tried
users.specialID = gender;
but that changes the specialID
property of the users object every single time a user connects. It doesn't add a new property/value pair (who's property is the specialID
(socket.id
) and who's value is the gender of the user). It sounds kind of stupid but I don't know how to do it.
回答1:
Try this:
users['your key'] = gender;
来源:https://stackoverflow.com/questions/31912657/appending-a-key-value-pair-to-a-javascript-object