[英]Undefined errors using Node.js, Mongoose, and Discord.js [Cannot read property of undefined]
[英]Node.js + Discord.js: Cannot read property 'class' of undefined
我對變量有疑問。 我正在研究 Discord RPG 機器人,但遇到了玩家數據問題。 當我使用控制台啟動機器人並發送消息以構建我的統計信息時,控制台將返回
C:\Users\willi\OneDrive\Desktop\discord-bot\homies.js:395
player[id].class = reply;
^
TypeError: Cannot set property 'class' of undefined
我使用下面的代碼。 這是整個程序的一個片段。 這需要的所有文件都存在。
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
const fs = require('fs');
const player = fs.readFileSync('user.json', 'utf-8');
client.on('message', message => {
var id = message.author.id;
if (player[id] === undefined) {
player[id] = {
username: message.author.username,
class: undefined,
xp: 0,
lvl: 1,
xpReq: 100 + this.lvl * 75,
hp: 0,
maxHp: 0,
str: 0,
def: 0,
int: 0,
dex: 0,
luck: 0,
mana: 0,
maxMana: 0,
equip: {
top: undefined,
bottom: undefined,
hand: undefined,
acc1: undefined,
acc2: undefined
},
spellcaster: undefined,
spells: []
};
var authorVerifier = m => m.author.id === id;
var classAnswer = message.channel.createMessageCollector(authorVerifier, { time: 300000, max: 1 });
var classInterpreter = function(reply) {
if (reply !== 'fighter' && reply !== 'adventurer' && reply !== 'mage'
&& reply !== 'healer' && reply !== 'rouge' && reply !== 'tank') {
return message.channel.send('That was not a valid class!');
}
else {
player[id].class = reply;
fs.writeFileSync('user.json', player[id], (err) => {
if (err) throw err;
});
}
}
classAnswer.on('collect', m => classInterpreter(m.content));
}
});
我嘗試用message.author.id
替換id
,但無濟於事。 請幫忙!
您可以通過將播放器數組傳遞給
classInterpreter
function 來解決它,並使用它來設置player[id].class
值。
classAnswer.on('collect', m => classInterpreter(m.content, player));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.