[英]Javascript: How to add array values to object property
Following code is for socket.io server in node.js 以下代码适用于node.js中的socket.io服务器
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};
io.on('connection', function(socket){
socket.on('game', function(data){
gamename[data.gamename]=data.number; //problem is here
});
});
gamename=name of the game; gamename =游戏名称; number= user id;
number =用户ID;
and I am emitting game event in the client side with some data (includeing gamename, and number)whenever a connection is established with the server. 每当与服务器建立连接时,我在客户端发出一些数据(包括游戏名称和号码)的游戏事件。 So whenever a new client connects to the server the game event is triggered in the server.
因此,每当新客户端连接到服务器时,在服务器中触发游戏事件。 In the game event in the server side I want to push "number" to the object property gamename(variable).
在服务器端的游戏事件中,我想将“数字”推送到对象属性gamename(变量)。
example: 例:
var games={};
whenever there is a connection for example for the game poker with user id 34 I want to do var gamename='poker'; 每当有用户ID为34的游戏扑克连接时,我想做var gamename ='poker';
gamename[gamename] -> I want this automatically created as array, or anything, but I want to push user id's.
the resulting objecting should be. 产生的反对应该是。
games={'poker' : [34]};
If I one more user connects for poker with user id 45, 如果我再一个用户连接用户ID为45的扑克,
games={'poker' : [34, 45]};
and If aa user connects for game cricket with user 67 如果用户用户67连接游戏板球
games={'poker' : [34, 45],'cricket' : [67]};
Initial object 初始对象
games={};
after some connections(there can be n number of connections) 一些连接后(可以有n个连接)
games={'poker' : [34, 45],'cricket' : [67]};
If my question is not clear I will explain it in detail if anybody asks. 如果我的问题不清楚,我会详细解释,如果有人问。 Thanks in advance
提前致谢
Like this: 像这样:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};
io.on('connection', function(socket){
socket.on('game', function(data){
gamename[data.gamename] = gamename[data.gamename] || [];
gamename[data.gamename].push( data.number ); //no more problem
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.