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

如何检查JavaScript数组中存在于指定字符串中的元素?

提取数组与字符串的共同短语解决方案

先看你代码里的几个问题:

  • userInput 赋值少了等号,正确写法是 userInput = "hey good morning bro";
  • 循环里用 userInput.includes(i) 是错误的,i 是数组索引,应该检查 myArray[i] 是否在字符串里
  • 没有把 intersect 初始化为数组,没法收集匹配的结果,你现在只是每次把它改成布尔值
  • 代码最后多了一个多余的 }

下面是两种正确的实现方式:

方式一:for循环实现

var userInput, myArray, intersect;
userInput = "hey good morning bro"; // 修正赋值语法
myArray = ["today", "morning", "good", "good morning"];
intersect = []; // 初始化为空数组

for (let i = 0; i < myArray.length; i++) {
  const currentPhrase = myArray[i];
  if (userInput.includes(currentPhrase)) {
    intersect.push(currentPhrase); // 符合条件就加入新数组
  }
}

console.log(intersect); // 输出 ["morning", "good", "good morning"]

方式二:数组filter方法(更简洁的现代写法)

const userInput = "hey good morning bro";
const myArray = ["today", "morning", "good", "good morning"];

// filter会自动遍历数组,返回所有满足条件的元素
const intersect = myArray.filter(phrase => userInput.includes(phrase));

console.log(intersect); // 输出 ["morning", "good", "good morning"]

两种方法都能得到你想要的结果,filter方法更简洁,是现在JavaScript里处理数组筛选的常用方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:25:12