我已经阅读了一些问题和答案,以便与我的要求有关,但我认为他们不完全回答我的问题。
我想创建一个新的全局数组,如果它不存在可变名称。
我当前的代码是
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"};
但这不起作用,每次都创建新数组。
您要做不是想要创建全局变量。您可以将房间作为索引添加到对象中,并从对象中读取以获取房间中的所有用户。
如果要使用房间创建"全局"数组,请使用以下内容:
(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);
}) ();
小提示:切勿污染全局范围,除非某些一般变量应全局。
这样的事情:
function NewArray (RoomId, UserId, UsrName){
RoomId = RoomId || [];
RoomId [UserId] = UsrName;
return RoomId;
}
您的数组检查可能是错误的。而是使用此:
RoomID = Object.prototype.toString.call(RoomID) === '[object Array]' ? RoomID : [];
您可以执行以下操作:
function NewRoom(RoomID, UserID, Usrname)
{
if($.isArray(RoomID ))
{
RoomID[UserID] = Usrname;
return RoomID;
}
else
{
RoomID=[];
RoomID[UserID] = Usrname;
return RoomID;
}