var roles = {
Guest: ["CAN_REGISTER"],
Player: ["CAN_LOGIN", "CAN_CHAT"],
Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};
这是我的对象,我正在尝试检查用户是否具有特定的权限
get_perms: function(player, perm) {
let arrayLength = accounts.length;
let name = player.name;
if (arrayLength == 0 && (perm == "CAN_CHAT" || perm == "CAN_LOGIN" || perm == "CAN_KICK")){
return false;
}
for (var i = 0; i < arrayLength; i++)
{
if (accounts[i][0] == name)
{
for (var key in roles)
{
if (roles.hasOwnProperty(key))
{
if (accounts[i][2] == key){
if (roles[key] == perm){
for (var x = 0; x < roles[key].length; x++){
if (roles[key][x] == perm){
return true;
}
}
}
}
}
}
}
else{
return false;
}
}
}
account[i][2]
是与名称匹配的播放器的角色,我正在尝试检查该角色是否有perm
发送给该函数,例如"CHAT_PERMS"
答案 0 :(得分:1)
const roles = {
Guest: ["CAN_REGISTER"],
Player: ["CAN_LOGIN", "CAN_CHAT"],
Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};
const arr = Object.keys(roles).reduce((acc, cur) => [...acc, ...roles[cur]], []);
console.log(arr);
const rightSet = new Set(arr);
console.log(rightSet.has("CAN_CHAT"))
这是我使用ES6的解决方案:
[ "CAN_REGISTER", "CAN_LOGIN", "CAN_CHAT", "CAN_KICK", "CAN_LOGIN", "CAN_CHAT" ]
has()
功能检查Set
答案 1 :(得分:0)
使用for-loop
和函数includes
检查角色和权限。
var roles = {
Guest: ["CAN_REGISTER"],
Player: ["CAN_LOGIN", "CAN_CHAT"],
Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};
var playerRoles = ['Admin', 'Guest'];
var perm = 'CAN_LOGIN';
var found = false;
for (var role of playerRoles) {
if ((found = roles[role].includes(perm))) {
console.log("Permission '"+perm+"' found in Role '" + role + "'");
break;
}
}
if (!found) {
console.log("Permission '"+perm+"' didn't found");
}