如何使用 JavaScript 在数组中查找特定单词?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/6 7:40:17

要查找数组中的特定单词,可以使用 includes()。我们有以下数组 −

var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];

现在,以下是一个数组,其中包含我们需要在上述 “sentence” 数组中搜索的单词 −

var keywords = ["John", "AUS", "JavaScript", "Hockey"];

示例

以下是代码 −

var keywords = ["John", "AUS", "JavaScript", "Hockey"];
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
const matched = [];
for (var index = 0; index < sentence.length; index++) {
   for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) {
      if (sentence[index].includes(keywords[outerIndex])) {
         matched.push(keywords[outerIndex]);
      }
   }
}
console.log("The matched keywords are==");
console.log(matched);

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo226.js。

输出

输出如下 −

PS C:\Users\Amit\JavaScript-code> node demo226.js
The matched keywords are==
[ 'John', 'JavaScript', 'Hockey' ]

相关文章


有用资源