You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断用户输入数组是否包含触发词并执行对应函数?

需求说明

我有两个数组:

  • 固定触发词数组:const triggerWord = ["what", "how", "where", "who", "can"];
  • 用户输入分割数组:const myArray = query.split(" ");(由用户输入字符串query按空格分割生成)

需要实现逻辑:如果myArray(已转小写为lowercaseMyArray)包含任意triggerWord里的元素,就调用questionFunction(lowercaseMyArray);否则调用statementFunction(lowercaseMyArray)。


你现有写法的问题分析

写法1:Switch Case

switch (lowercaseMyArray.includes())存在两处错误:

  • includes()必须传入要查找的元素参数,空调用无意义;
  • switch的表达式是布尔值(includes()的返回结果),但case里写的是字符串,两者类型不匹配,逻辑完全不成立;
  • 另外代码只覆盖了前4个触发词,漏掉了"can"。

写法2:If Statement

lowercaseMyArray.includes(triggerWord[0] || triggerWord[1] || triggerWord[2] || triggerWord[3], 2)逻辑错误:

  • triggerWord[0] || ...会直接返回第一个真值(也就是"what"),实际只判断了是否包含"what";
  • 第二个参数是查找的起始索引,写2会跳过前两个元素,完全不符合需求。

写法3:Bool and If Statement

lowercaseMyArray.includes(triggerWord)错误:

  • includes()只能接收单个元素作为参数,不能直接传入数组,因此这个判断永远返回false。

正确实现方式

方式1:用some()遍历判断(最直观)

// 先将用户输入的所有单词转小写,统一匹配规则
const lowercaseMyArray = myArray.map(word => word.toLowerCase());
// 判断触发词数组中是否有任意元素存在于用户输入数组中
const isQuestion = triggerWord.some(word => lowercaseMyArray.includes(word));

if (isQuestion) {
  questionFunction(lowercaseMyArray);
} else {
  statementFunction(lowercaseMyArray);
}

some()会遍历triggerWord数组,只要有一个元素满足条件就返回true,完美匹配需求。

方式2:用Set优化查找性能(适合数据量大的场景)

const lowercaseMyArray = myArray.map(word => word.toLowerCase());
// 将用户输入转成Set,查找效率从O(n)提升到O(1)
const inputWordSet = new Set(lowercaseMyArray);
const isQuestion = triggerWord.some(word => inputWordSet.has(word));

if (isQuestion) {
  questionFunction(lowercaseMyArray);
} else {
  statementFunction(lowercaseMyArray);
}

方式3:用正则直接匹配原字符串(无需提前分割数组)

// 构建正则:匹配任意触发词作为独立单词,忽略大小写
const triggerRegex = new RegExp(`\\b(${triggerWord.join('|')})\\b`, 'i');
const isQuestion = triggerRegex.test(query);

// 按需转小写分割数组
const lowercaseMyArray = query.toLowerCase().split(" ");
isQuestion ? questionFunction(lowercaseMyArray) : statementFunction(lowercaseMyArray);

\\b确保匹配完整单词(避免误判"whatsoever"这类包含触发词的长单词),'i'标志实现忽略大小写匹配。

内容的提问来源于stack exchange,提问作者onaikepo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:25:34