JavaScript 按多個字串篩選陣列?


要按多個字串篩選陣列,可以使用 for 迴圈以及 indexOf()。以下為程式碼:-

示例

var details = [
   'My first Name is John and last Name is Smith',
   'My first Name is John and last Name is Doe',
   'Student first Name is John and last Name is Taylor'
];
var isPresent;
var records = [];
var matchWords = ['John', 'Doe'];
for (var index = 0; index < details.length; index++){
   isPresent = true;
   for (var outer = 0; outer< matchWords.length; outer++) {
      if (details[index].indexOf(matchWords[outer]) === -1) {
         isPresent = false;
         break;
      }
   }
   if (isPresent){
      records.push(details[index]);
   }
}
console.log(records)

要執行上述程式,你需要使用以下命令:-

node fileName.js.

在這裡,我的檔名是 demo151.js。

輸出

這將生成以下輸出:-

PS C:\Users\Amit\JavaScript-code> node demo151.js
[ 'My first Name is John and last Name is Doe'

更新於: 11-Sep-2020

592 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始吧
廣告
© . All rights reserved.