我在json中有一个数组,当我试图用下面的代码访问它时,它会出现多个单词的错误.有人能帮忙修复代码吗



它显示的错误代码是:

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中,则在for循环后,i变为spell.spelldictionary.length,执行msg.channel.send(spell.spelldictionary[i][1])会导致错误。

您可以通过在for循环中将msg.channel.send移动到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]);
}

最新更新