Reputation: 3485
I'm using node js to create a multi player game website. so every time a socket is connected I add that socket in an array like this
var users = [];
var games = [];
var joinKey = [];
var key = 0;
var usersKey = 101;
var gamesKey = 201;
io.sockets.on('connection', function (socket) {
socket.on('connect', function(){
console.log('connect');
var clientId = usersKey;
socket.clientId = clientId;
users[usersKey] = socket;
usersKey++;
socket.emit('getClientId', clientId);
console.log(socket.clientId + ' connected');
console.log('Total users: ' + users.length);
});
here total users shows 102 as user key is 101 and it automatically tales blank values from 0 to 100. this is not normal i guess. also if I retrieve the socket from other array using index, it is undefined if the index is string, like 'g201'
socket.on('createNewGame', function(){
var game = [];
var clientId = socket.clientId;
game[clientId] = socket;
console.log(game);
var gameId = 'g' + gamesKey;
gamesKey++;
games[gameId] = game;
console.log('Total Games: ' + games.length)
socket.gameId = gameId;
var publicKey = ++key;
joinKey[publicKey] = gameId;
socket.emit('gameCreated', publicKey);
});
I'm not getting how to insert and fetch if this is the behavior of array here
Upvotes: 0
Views: 131
Reputation: 7905
To answer your first point:
An array uses numerical indices running from 0.
When you manually place a value in at 101 it will fill the rest of the values in since it has to run from 0, these will be padded with undefined. (as per Andrew Barretts comment)
To answer your second point:
If you need to have an "associate array" or at least what people refer to as an associative array then you should use objects.
game= new Object();
game["g1"]=...
game["g25"]=...
...
Upvotes: 2