[英]Is there a way to compare the strings in two arrays to see if one of them is present within the other
I have two arrays.我有两个 arrays。
First one: const triggerWord = ["what", "how", "where", "who", "can"];
第一个:
const triggerWord = ["what", "how", "where", "who", "can"];
Second one: const myArray = query.split(" ");
第二个:
const myArray = query.split(" ");
- it is created after splitting the user input in this case called query. - 它是在拆分用户输入后创建的,在这种情况下称为查询。
One is a fixed number of strings, that will not change as they are the trigger words.一种是固定数量的字符串,不会因为它们是触发词而改变。 The other array is an input string that has been split into an array, separated by a space.
另一个数组是一个输入字符串,已拆分为一个数组,以空格分隔。
I am trying to build some sort of control flow that if any of the triggerWords are present within the myArray then it should call a specific function call the questionFunction().我正在尝试构建某种控制流,如果 myArray 中存在任何 triggerWords,那么它应该调用特定的 function 调用 questionFunction()。 However the
else
is that is should call the statement function. Here are the functions I have attempted:然而,
else
应该调用语句 function。以下是我尝试过的功能:
#1: Switch Case: #1:开关盒:
switch (lowercaseMyArray.includes()) {
case triggerWord[0].toString():
questionFunction(lowercaseMyArray);
break;
case triggerWord[1].toString():
questionFunction(lowercaseMyArray);
break;
case triggerWord[2].toString():
questionFunction(lowercaseMyArray);
break;
case triggerWord[3].toString():
questionFunction(lowercaseMyArray);
break;
default:
statementFunction(lowercaseMyArray);
#2: If statement #2: If 语句
if (lowercaseMyArray.includes(triggerWord[0] || triggerWord[1] || triggerWord[2] || triggerWord[3], 2)) {
//alert("This is a question");
questionFunction(lowercaseMyArray);
//passe onto questionFunction
} else {
statementFunction(lowercaseMyArray);
//alert(myArray);
}
#3: Bool and If Statment #3: Bool 和 If 语句
var lowercaseMyArrayBool = lowercaseMyArray.includes(triggerWord);
if (lowercaseMyArrayBool === true) {
questionFunction(lowercaseMyArray);
} else {
statementFunction(lowercaseMyArray);
}
The idea being that if it contains a trigger word then the input must be a question and therefore treated as such.这个想法是,如果它包含一个触发词,那么输入必须是一个问题,因此被这样对待。 However if it doesn't contain the trigger words then the input is a statement and must be treated as that.
但是,如果它不包含触发词,则输入是一个语句并且必须被视为该语句。
Any help or pointers will be greatly appreciated.任何帮助或指示将不胜感激。
Resolved this with the following code:使用以下代码解决了这个问题:
const intersection = triggerWord.filter(element => lowercaseMyArray.includes(element)).length;
const intersectionBool = Boolean(intersection);
I just needed to cast the filtered array length as a Boolean, to get an accurate true or false result.我只需要将过滤后的数组长度转换为 Boolean,即可获得准确的 true 或 false 结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.