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


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

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

现在, 下面是一个数组, 里面有我们需要在上面的 “句子” 数组中查找的单词 −

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' ]

上次更新: 03-Oct-2020

930 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.