繁体   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