Node.js + Discord.js:无法读取未定义的属性“类”

问题描述

我对变量有疑问。我正在使用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));
    }
});

我尝试将id替换为message.author.id,但无济于事。请帮忙!

解决方法

您可以通过将播放器数组传递到classInterpreter来解决此问题 函数,并使用它来设置player[id].class的值。

classAnswer.on('collect',m => classInterpreter(m.content,player));

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...