gpt4 book ai didi

Javascript - 如何迭代对象中键的值?

转载 作者:行者123 更新时间:2023-12-03 02:22:53 25 4
gpt4 key购买 nike

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] 是与名称匹配的玩家 Angular 色,我正在尝试检查该 Angular 色是否具有发送到的 perm函数,例如“CHAT_PERMS”

最佳答案

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 的解决方案:

  1. 使用reduce和数组扩展语法创建一个平面数组,它为您提供[ "CAN_REGISTER", "CAN_LOGIN", "CAN_CHAT", "CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
  2. 将此数组保存在集合中
  3. 使用has()函数检查Set是否正确

关于Javascript - 如何迭代对象中键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com