Tioww Tioww - 4 months ago 38
Javascript Question

How can i solve id giving problems

I have a problem. I'am giving ids with var nextId = players_online.length; but if as example: player one connect to the game he gets id:1, second player gets id:2, then if first player disconnect other connected player gets same id:2

P.S also I can't do var nextId = nextId+1; because i draw players by their id players_online[id]. As example: player connect to the game he gets higher and higher id player = {id}, but then other player disconnect there will be no such id players_online[10] because one disconnected there is no player 10 in array...

Any ideas?( Somehow i have to give them id if it's not used by other player also it's can't by higher then players_online.length)


You can use JS object with integer keys instead of an array.

And generate nextId as maximal key + 1.

var connections = {
    "1": { /* connection details */ },
    "2": { /* connection details */ },
    "4": { /* connection details */ }

// get all keys
var keys = Object.keys(connections);

// check for key existence
console.log("2" in connections);
console.log("3" in connections);

// delete connection 4
delete connections["4"];

function getNextId(obj) {
    var keys = Object.keys(obj).map(function(key) {
        return Number(key)
    var maxKey = Math.max.apply(null, keys);
    return maxKey + 1;

// get next id
var nextId = getNextId(connections);

// add new connection
connections[nextId] = { /* connection details */ };

Or you can use Guid as an id: https://www.npmjs.com/package/guid

Then simply generate new guid for new connection.