user3182138
user3182138

Reputation:

create global array (not associative array) with variable name in Javascript

I have already read some questions and answers on SO that are related to what I'm asking, but I don't think they answer exactly my question.

I want to create a new global array if it doesn't exists with a variable name.

My Current Code is

function NewRoom(RoomID, UserID, Usrname)
{
    //Check if RoomID array is already declared or not and create new one if not
    //and add UserID and Usrname in it and then return it

    //My Current Code from a SO answer
    RoomID = ( typeof RoomID != 'undefined' && RoomID instanceof Array ) ? RoomID : [];
    RoomID[UserID] = Usrname;
    return RoomID;
}

var users = ['abc','def','ghi'];
for(var i=0; i<3; i++)
{
    NewRoom('Room2', i, users[i]);
}

var users2 = ['jkl','mno','pqr'];
for(var i=0; i<3; i++)
{
    NewRoom('Room3', i, users2[i]);
}

console.log(users);
console.log(users2);

My Console always show last inserted results like for above users and users2 it is

Object { 2="ghi"};
Object { 2="pqr"};

but this does not work and create new array everytime.

Upvotes: 0

Views: 1269

Answers (4)

Balachandran
Balachandran

Reputation: 9637

You could do the following:

function NewRoom(RoomID, UserID, Usrname)
{
   if($.isArray(RoomID ))
   {
       RoomID[UserID] = Usrname;
       return RoomID;
   }
   else
   {
       RoomID=[];
       RoomID[UserID] = Usrname;
       return RoomID;
   }

Upvotes: 0

Hidde
Hidde

Reputation: 11941

You do NOT want to create global variables. You can add the rooms as indices to an object, and read from the object to get all the users in the room.

If you want to create a 'global' array with the rooms, use the following:

(function () {
    var rooms = {};

    function setRoom(RoomID, UserID, Usrname) {
        if (typeof rooms[RoomID] === 'undefined') {
            rooms[RoomID] = {};
        }
        rooms[RoomID][UserID] = Usrname;
    }

    var users = ['abc','def','ghi'];
    for(var i=0; i<3; i++) {
        setRoom('Room2', i, users[i]);
    }

    var users2 = ['jkl','mno','pqr'];
    for(var i=0; i<3; i++) {
        setRoom('Room3', i, users2[i]);
    }

    console.log(rooms['Room2']);
    console.log(rooms['Room3']);
    console.log(rooms);
}) ();

Small tip: never pollute the global scope, except when some general variable SHOULD be global.

Upvotes: 2

gtournie
gtournie

Reputation: 4382

Your array check is probably wrong. Use this instead:

RoomID = Object.prototype.toString.call(RoomID) === '[object Array]' ? RoomID : [];

Upvotes: 0

Alex Shilman
Alex Shilman

Reputation: 1547

What about something like this:

function NewArray (RoomId, UserId, UsrName){
  RoomId = RoomId || [];
  RoomId [UserId] = UsrName;
  return RoomId;
 }

Upvotes: 0

Related Questions