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'
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP