简体   繁体   English

Array.prototype.includes() 通配符选项?

[英]Array.prototype.includes() wildcard options?

I have the following code which filters an array by tags (specifically 2 tags).我有以下代码按标签(特别是 2 个标签)过滤数组。 It works well with word strings but I would like to add the ability to use some sort of wildcard.它适用于字符串,但我想添加使用某种通配符的功能。 For example to filter all tags that start with "-" (my attempt at grouping the tags).例如过滤所有以"-"开头的标签(我尝试对标签进行分组)。 Using this string here doesn't work.在此处使用此字符串不起作用。 I have also tried using a regular expression eg.我也尝试过使用正则表达式,例如。 /^-/ but that doesn't work either. /^-/但这也不起作用。

I have discovered that Array.prototype.includes() differs from String.prototype.includes() in that it only captures whole "words" so that probably explains why it's not working but was I wondering if there was some way to do this?我发现Array.prototype.includes()String.prototype.includes() Array.prototype.includes()不同之处在于它只捕获整个“单词”,所以这可能解释了为什么它不起作用但我想知道是否有某种方法可以做到这一点?

 var cards = [ { cardId: 1001, tags: ["_easy", "-casual"], videoId: "rO5BVRK6KMo", }, { cardId: 1002, tags: ["_hard", "-polite"], videoId: "qK--SAlGD0Q", } ] var ReviewtagFilter = function() { let reviewsTagged = []; let tagLevel = "_easy"; let tagTopic = "-casual"; //***"-" doesn't work to get -casual & "-polite" //console.log("tagLevel: ", tagLevel + "tagTopic" , tagTopic) reviewsTagged = cards.filter( data => data.tags.includes(tagLevel) && data.tags.includes(tagTopic) ); console.log(reviewsTagged) }; ReviewtagFilter();

As others mentioned, you cannot use regex with Array.includes() .正如其他人提到的,您不能将正则表达式与Array.includes() The simplest way would be to use a some() or every() (depending on what do you want to achieve) instead:最简单的方法是使用some()every() (取决于您想要实现的目标):

var ReviewtagFilter = function() {
  let reviewsTagged = [];
  let tagLevel = "_easy";  
  let tagTopic = /^-/; 

  reviewsTagged = cards.filter(
    data => data.some(tag => tag.match(tagTopic)) && data.tags.includes(tagLevel)
  );
  console.log(reviewsTagged)
};

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

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