我有一个房间对象,里面的那个对象有很多房间数组,而且每个房间都有用户元素。
var rooms = {"room1":["user1","user2"],"room2":["user1","user2","user3"]};
如何在调用时编写一个从rooms数组中删除特定用户的函数?
function leaveRoom(user,room){
if(typeof room != "undefined"){
//remove user from the specific room ONLY if room argument is passed
} else {
//remove user from all rooms
}
}
我曾尝试将splice与元素的索引一起使用,但它不起作用。
Array.prototype.remove = function(value) {
if (this.indexOf(value)!==-1) {
this.splice(this.indexOf(value), 1);
return true;
} else {
return false;
};
}
var roomName="room1",
userName="user1";
rooms[roomName].remove(userName);
实际上我甚至不确定它是否是一个对象或数组。请帮助谢谢
答案 0 :(得分:1)
您可以使用for..in
循环,delete
,Array.prototype.filter()
从数组中删除值为undefined
的元素
var rooms = {
"room1": ["user1", "user2"],
"room2": ["user1", "user2", "user3"]
};
function leaveRoom(user, room, obj) {
if (room && Array.isArray(obj[room])) {
delete obj[room][obj[room].indexOf(user)];
} else {
for (var prop in obj) {
delete obj[prop][obj[prop].indexOf(user)];
}
};
for (var prop in obj) {
obj[prop] = obj[prop].filter(Boolean)
}
}
leaveRoom("user1", "room1", rooms);
console.log(rooms); // remove `"user1"` from `"room1"`
// pass `null` as second parameter to remove `user` from all rooms
leaveRoom("user2", null, rooms); // remove `"user2"` from all rooms
console.log(rooms);
答案 1 :(得分:1)
我使用for..in
循环和slice
制作了它。希望这会对你有所帮助
var rooms = {
"room1": ["user1", "user2"],
"room2": ["user1", "user2", "user3"],
"room3": ["user1", "user2", "user3"]
};
function leaveRoom(user, room) {
for (var eachroom in rooms) {
if (eachroom == room) {
var users = (rooms[eachroom]);
for (var user_index in users) {
if (users[user_index] == user) {
users.splice(user_index, 1);
break;
}
}
rooms[eachroom] = users;
break;
}
}
//checking whether the user is removed
for (var i in rooms) {
var j = (rooms[i]);
alert(i+":"+j);
}
}
leaveRoom('user2', 'room3');
链接到jsfiddle:https://jsfiddle.net/kannanore/s6u6m5fn/3/