表示されるエラーコードは次のとおりです。
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
用ループ、および実行後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]);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加