[英]How can I check if an object contains at least one key whose value contains a substring in JavaScript?
[英]How can one check if an array contains a substring?
是否可以檢查字符串數組是否包含子字符串? 我知道如何查找一個數組是否具有完整的字符串匹配項(使用$ .inArray,arr.includes,arr.indexOf等...),但是這些不將子字符串與字符串數組匹配(至少對我而言) )。
如果我有一個帶有以下選項的<select multiple>
元素:
positive (selected)
positron (selected)
negative
negatron
如何為我的多選項數組是否包含子字符串pos
布爾值表示在選擇中同時存在positve
和positron
?
我希望能夠根據是否做出某些選擇向用戶提出一些其他問題,但我不想編寫一堆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.