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