簡體   English   中英

如何檢查數組是否包含子字符串?

[英]How can one check if an array contains a substring?

是否可以檢查字符串數組是否包含子字符串? 我知道如何查找一個數組是否具有完整的字符串匹配項(使用$ .inArray,arr.includes,arr.indexOf等...),但是這些不將子字符串與字符串數組匹配(至少對我而言) )。

如果我有一個帶有以下選項的<select multiple>元素:

positive (selected)
positron (selected)
negative
negatron

如何為我的多選項數組是否包含子字符串pos布爾值表示在選擇中同時存在positvepositron

我希望能夠根據是否做出某些選擇向用戶提出一些其他問題,但我不想編寫一堆if / then語句來覆蓋各種字符串。

您可以使用indexOf檢查數組元素是否包含子字符串

 var testData = ['positive', 'negative'] testData.forEach(function(item) { if (item.indexOf('pos') !== -1) { console.log('Hava data') } }) 

Array.prototype具有非常有用的.filter函數。

 const arr = ['positive', 'positron', 'negative', 'negatron']; function findMatches() { let searchVal = document.getElementById('test').value; let res = arr.filter(el => el.indexOf(searchVal) > -1); document.getElementById('result').innerHTML = res.join(', '); } 
 <input type="text" id="test" /> <button type="button" onclick="findMatches()">Find</button> <br /> Array: ['positive', 'positron', 'negative', 'negatron']<br /> <span id="result"></span> 

然后將擴展邏輯應用於過濾后的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM