如何在陣列中查詢特定的單詞,用 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.