我将xp存储在json文件中以进行练习。如何显示前10位用户?我第一次 本来希望可以进行排序,但我不知道这样会更有效率。
let xpAdd = Math.floor(Math.random() * 9) + 8;
if(!xp[message.author.id]) {
xp[message.author.id] = {
xp:0,
level:1
};
}
let curxp = xp[message.author.id].xp;
let curlvl = xp[message.author.id].level;
let nxtLevel = xp[message.author.id].level * 300;
xp[message.author.id].xp = curxp + xpAdd;
fs.writeFile("./xp.json", JSON.stringify(xp), (error) => {
if(error) console.log(error);
});
这是我存储的代码
并以此显示xp的水平
if(!xp[message.author.id]) {
xp[message.author.id] = {
xp: 0,
level:1
};
}
let curxp = xp[message.author.id].xp;
let curlvl = xp[message.author.id].level;
let nxtLevelXp = curlvl * 300;
let difference = nxtLevelXp - curxp;
答案 0 :(得分:0)
我建议您将对象转换为数组,以便可以按自己的喜好对其进行格式化和排序。
// sample object
// I'm going to show the top three in this example for the interest of space
const xp = {
"ID #1": {
level: 3,
xp: 300,
},
"ID #2": {
level: 4,
xp: 400,
},
"ID #3": {
level: 2,
xp: 200,
},
"ID #4": {
level: 1,
xp: 100,
},
};
// sort entries in order of exp (descending), then single out the top three
let entries = Object.entries(xp).sort(([, a], [, b]) => b.xp > a.xp ? 1 : -1).slice(0, 3);
// map entries to the prefered format using the data in their objects
// (in your actual command, you should use `client.users.cache.get(id).tag`,
// but since I don't have access to the client object here, I'm just writing `id`
entries = entries.map(([id, { level, xp }], idx) => `${idx + 1} - ${id} (level ${level}; ${xp} xp)`);
// join each user by a line break
console.log(entries.join('\n'));
答案 1 :(得分:0)
if(!xpd[message.author.id]) {
xpd[message.author.id] = {
xp: 0,
level:1
};
}
const xp = {
"xpd[message.author.id]":{
level: xpd[message.author.id].level,
xp: xpd[message.author.id].xp,
},
"xpd[message.author.id]": {
level: xpd[message.author.id].level,
xp: xpd[message.author.id].xp,
},
"xpd[message.author.id]": {
level: xpd[message.author.id].level,
xp: xpd[message.author.id].xp,
},
"xpd[message.author.id]": {
level: xpd[message.author.id].level,
xp: xpd[message.author.id].xp,
},
};
let entries = Object.entries(xp).sort(([, a], [, b]) => b.xp > a.xp ? 1 : -1).slice(0, 3);
entries = entries.map(([id, {level, xp }], idx) => `${idx + 1} - ${id} (${level}; ${xp} xp)`);
console.log(entries.join('\n'));
我尝试了您的解决方案,但只显示了一个用户,我应该添加什么?