簡體   English   中英

檢查數組Javascript中是否存在子字符串

[英]Check if a substring exists in an array Javascript

我想檢查我的數組中是否存在字符串。

我的Javascript代碼:

if(Ressource.includes("Gold") === true )
         {
             alert('Gold is in my arrray');
         }

所以Ressource是我的數組,這個數組包含:

資源[“ Gold 780”,“ Platin 500”] //我打印了它以檢查它是否為真

我不明白為什么我的測試if(Ressource.includes("Gold") === true無法正常工作。

最好的問候,我希望有人知道這有什么問題。

includes數組方法檢查字符串"Gold"是否作為數組中的一項 includes ,而不檢查其中一個數組項是否包含子字符串。 您想為此使用some includes字符串方法

Ressources.some(res => res.includes("Gold"))

您應該遍歷數組,直到發現值是否存在。

if (Ressource.some(x => x.includes("Gold") === true)) {
    alert('Gold is in my arrray');
}

另一種方法是使用Array.prototype.find()和一個簡單的RegExp 這將返回包含搜索詞的元素的值。 如大多數答案中所述,如果您的搜索詞與數組元素Gold 780完全匹配,則Array.prototype.includes()起作用。

 let Ressource = ["Gold 780","Platin 500"] ; let found = Ressource.find(function(element) { let re = new RegExp('Gold'); return element.match(re); }); console.log(found); // Working example of Array.prototype.includes() if(Ressource.includes("Gold 780")) { console.log('Gold is in my arrray'); } 

工作小提琴

您的問題是數組中的字符串中包含數字和Gold。 嘗試像這樣使用正則表達式:

 var Ressource = ["Gold 232331","Iron 123"] if(checkForGold(Ressource) === true ) { console.log('Gold is in my array'); } else { console.log('Gold is not in my array'); } function checkForGold(arr) { var regex = /Gold\\s(\\d+)/; return arr.some(x=>{if(x.match(regex))return true}); } 

MDN文檔對正則表達式很好的指導 試試這個吧。

暫無
暫無

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

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