将键值对附加到javascript对象 [英] Appending a key value pair to a javascript object

查看:100
本文介绍了将键值对附加到javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于此问题。但是,我想向对象添加属性,但是我不知道该属性的名称。情况是,当用户连接随机的 socket.id socket.io应用程序中的名称空间。 c $ c>的生成是为了能够将该用户与其他用户区分开,当用户连接时,他们还将其性别发送到服务器(通过 socket.emit ),现在我想创建一个对象,以跟踪用户的套接字ID和性别。

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)

现在我尝试了

users.specialID = gender;

,但这更改了 b的 specialID 属性用户在用户每次连接时都会反对。它不会添加新的属性/值对(谁的属性是 specialID socket.id ),谁是值是用户的性别)。听起来有点愚蠢,但我不知道该怎么做。

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.

推荐答案

尝试一下:

users['your key'] = gender;

这篇关于将键值对附加到javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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