Kir*_*tsu 5 javascript node.js discord discord.js
我已经做了一些搜索,我在这里找到了一些帖子,但我的代码不想工作。基本上我正在制作一个不和谐的机器人,我想从一个 JSON 文件中随机选择一个对象。
这是我的命令:
const UserData = require('../data/users.js');
const monster = require('../data/monsters.json');
module.exports = {
name: 'battle',
aliases: ['fight'],
cooldown: 0,
description: 'User fights against a monster alone or in group',
execute(client, message, args) {
let enemy = monster[Math.floor(Math.random() * monster.length)]
UserData.findOne({
userID: message.author.id
}, (error, userdata) => {
if (error) console.log(error);
if (!userdata) {
return message.reply(`you don't have an account!`);
} else {
console.log(enemy);
return message.channel.send(`${enemy} spawned!`);
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 JSON 文件:
"1" : {
"name": "Blue Slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"2": {
"name": "Red slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"3": {
"name": "Green slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想手动将对象放入命令中,然后随机选择它们,它可以工作,如果我输入的不是“monster.length”,那么它也可以工作,但如果它应该是 3,我仍然没有定义。这样我也总是从monster.length 在控制台日志中获取未定义。我究竟做错了什么?
您的monsters.json文件包含一个对象,而对象没有lengths。但是,您可以将其转换为数组,使用Object.values()它返回给定对象自己的可枚举属性值的数组。
查看下面的片段:
let monsters = {
1: {
name: 'Blue Slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
2: {
name: 'Red slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
3: {
name: 'Green slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
};
function randomObject(obj) {
let arr = Object.values(obj);
return arr[Math.floor(Math.random() * arr.length)];
}
let enemy = randomObject(monsters);
console.log(enemy);Run Code Online (Sandbox Code Playgroud)