简体   繁体   English

检查数组Javascript中是否存在子字符串

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

I would like to check if a String exists in my array. 我想检查我的数组中是否存在字符串。

My Javascript Code : 我的Javascript代码:

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

So Ressource is my array and this array contains : 所以Ressource是我的数组,这个数组包含:

Ressource ["Gold 780","Platin 500"] // I printed it to check if it was true 资源[“ Gold 780”,“ Platin 500”] //我打印了它以检查它是否为真

I don't understand why my test if(Ressource.includes("Gold") === true don't work. 我不明白为什么我的测试if(Ressource.includes("Gold") === true无法正常工作。

Best regards, I hope someone knows what is wrong with this. 最好的问候,我希望有人知道这有什么问题。

The includes array method checks whether the string "Gold" is contained as an item in the array, not whether one of the array items contains the substring. includes数组方法检查字符串"Gold"是否作为数组中的一项 includes ,而不检查其中一个数组项是否包含子字符串。 You'd want to use some with the includes string method for that: 您想为此使用some includes字符串方法

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

You should loop through your array until you find out if your value exist. 您应该遍历数组,直到发现值是否存在。

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

Another approach would be to use Array.prototype.find() and a simple RegExp . 另一种方法是使用Array.prototype.find()和一个简单的RegExp That would return the value of the element holding the search term. 这将返回包含搜索词的元素的值。 As said in most answers Array.prototype.includes() works if your search term matches exactly the array element Gold 780 . 如大多数答案中所述,如果您的搜索词与数组元素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'); } 

Working Fiddle 工作小提琴

Your problem is that you have a number along with Gold in the string in your array. 您的问题是数组中的字符串中包含数字和Gold。 Try using regex like this: 尝试像这样使用正则表达式:

 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}); } 

The MDN docs have a excellent guide to regular expressions . MDN文档对正则表达式很好的指导 Try this instead. 试试这个吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM