js对象写入键值对,将键值对附加到javascript对象

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.

解决方案

Try this:

users['your key'] = gender;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值