它显示的错误代码是:
msg.channel.send(spell.spelldictionary[i][1])
^
TypeError:无法读取未定义的属性“ 1”
索引代码是:
const Discord = require('discord.js')
const bot = new Discord.Client()
const token = '';
const PREFIX = '%';
const spell = require('./spells.json')
bot.on('message', msg =>{
if(!msg.author.bot && msg.content.startsWith(PREFIX))
{
let args = msg.content.substring(PREFIX.length).split(" ");
switch(args[0])
{
case 'D&D':
switch(args[1])
{
case 'spellinfo':
let spellname = args.slice(2);
for(i = 0; i < spell.spelldictionary.length; i++)
{
if(spellname == spell.spelldictionary[i][0])
{
break;
}
}
msg.channel.send(spell.spelldictionary[i][1])
break;
}
break;
}
}
}
bot.login(token)
JSON文件如下:
{
"spelldictionary": [
["Acid Splash","a"],
["Aid","a"],
["Alarm","a"],
["Alter Self","a"],
["Animal Friendship","a"],
["Animal Messenger","a"],
["Animal Shapes","a"],
["Animate Dead","a"],
["Animate Objects","a"],
["Antilife Shell","a"],
["Antimagic Field","a"],
["Antipathy","a"],
["Arcane Eye","a"],
["Arcane Gate","a"],
["Arcane Lock","a"],
["Armour of Agathys","a"],
["Arms of Hadar","a"],
["Astral Projection","a"],
["Augury","a"],
["Aura of Life","a"],
["Aura of Purity","a"],
["Aura of Vitality","a"],
["Awaken","a"],
["Bane","a"]
]
}
任何帮助将不胜感激,但是由于我是一个初学者,所以我对JavaScript的了解不多,因此您可以尽量不要使答案过于复杂。
如果spellname
不在中spell.spelldictionary
,则i
成为spell.spelldictionary.length
for循环之后,并执行msg.channel.send(spell.spelldictionary[i][1])
导致错误。
您可以通过在for循环中移动msg.channel.send
before来避免它break
,从而在这种情况下不会发送任何消息。另外,最好i
在使用它之前明确声明,否则在代码变得更加复杂之后可能会导致一些意外错误。
let spellname = args.slice(2);
for(let i = 0; i < spell.spelldictionary.length; i++) // <<
{
if(spellname == spell.spelldictionary[i][0])
{
msg.channel.send(spell.spelldictionary[i][1]); // <<
break;
}
}
// do nothing here
为了防止这种错误,您可以尝试使用Array的某些方法。在这种情况下,您可能要使用array.find()。它返回满足测试功能的第一个元素,或者undefined
如果不存在这样的元素,则返回该元素。
在您的情况下,测试函数为elm => elm[0]==spell
,因此您可以将其重写为:
// `elm` is the same as `spell.spelldictionary[i]` in your code
const elm = spell.spelldictionary.find(elm => spellname==elm[0]);
if (elm !== undefined) { // if found
msg.channel.send(elm[1]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句