如何检查字符串是不是包含在数组中?不和谐.js
Posted
技术标签:
【中文标题】如何检查字符串是不是包含在数组中?不和谐.js【英文标题】:How to check if a string is included in an array? discord.js如何检查字符串是否包含在数组中?不和谐.js 【发布时间】:2021-07-23 16:39:43 【问题描述】:基本上我试图通过显示嵌入并等待答案来制作一个不和谐的机器人来制作琐事问题,我已将答案放在一个单独的文件中的数组中,possibleAnswersF
是包含答案的数组给你 5 分,possibleAnswersT
是包含给你 10 的答案的数组,而 possibleAnswers 是包含所有答案的数组,我尝试使用 possibleAnswersF.includes(collected)
但它不起作用,我试过了收集一个数组并以另一种方式使用includes()
,但它跳转到catch()
。
const MessageEmbed = require('discord.js');
//const talkedRecently = new Set();
const Characters = require('../../triviacharacterlist');
const points = require('../../points.json');
const fs = require('fs');
module.exports =
commands : ['trivia', 't'],
minArgs : 0,
maxArgs : 0,
callback : (msg, arguments, text) =>
function TriviaGuess(possibleAnswers, possibleAnswersF, possibleAnswersT, CharacterImgDir)
const guessCharacterString = "Guess character bo3";
let pointAmt1 = 5;
let pointAmt2 = 10;
const triviaEmbed = new MessageEmbed()
.setColor('#008fff')
.setTitle(guessCharacterString)
.setImage(CharacterImgDir)
msg.channel.send(triviaEmbed)
const filter = m => possibleAnswers.some(answer => m.content.toLowerCase().includes(answer));
msg.channel.awaitMessages(filter, max: 1, time: 15000, errors: ['time'] )
.then(collected =>
const fivePoint = `**Congrats**, $collected.first().author you got **5** points for guessing the character only!`;
const tenPoint = `**Congrats**, $collected.first().author you got **10** points for also guessing the series/game!`;
if (possibleAnswersF.includes(collected))
msg.channel.send(fivePoint);
points[msg.author.id] =
points: points[msg.author.id].points + pointAmt1
;
fs.writeFile('./points.json', JSON.stringify(points), (err) =>
if (err)
console.log(err)
);
if (possibleAnswersT.includes(collected))
msg.channel.send(tenPoint);
points[msg.author.id] =
points: points[msg.author.id].points + pointAmt2
;
fs.writeFile('./points.json', JSON.stringify(points), (err) =>
if (err)
console.log(err)
);
)
.catch(collected => msg.channel.send('too bad u took too long ya 3am'));
var characterRandom = 0;//Math.floor(Math.random() * 0);
if (characterRandom == 0)
TriviaGuess(Characters.CreeperVariants, Characters.CreeperVariantsF, Characters.CreeperVariantsT, Characters.CharacterImgs.creeperimg);
另一个包含数组的文件:
const CreeperVariants = [
'creeper',
'creeper minecraft',
'creeper mc'
]
const CreeperVariantsF = [
'creeper'
]
const CreeperVariantsT = [
'creeper minecraft',
'creeper mc'
]
【问题讨论】:
【参考方案1】:collected
是一个 Collection 扩展 Map,而不是一个字符串。您需要检查collected.first().content
。使用Array#some()
和String#includes
检查是否在字符串中找到任何数组元素。
if (possibleAnswersF.some(ans => collected.first().content.includes(ans)))
// Your code
【讨论】:
以上是关于如何检查字符串是不是包含在数组中?不和谐.js的主要内容,如果未能解决你的问题,请参考以下文章
如何检查一个字符串数组是不是包含 JavaScript 中的一个字符串? [复制]
如何检查字符串是不是包含 JavaScript 预定义数组中存在的子字符串?