如何使用 javascript includes 过滤掉不包含特定文本的文本

How do I use javascript includes to filter out text that does not include specific text

我有一个方法可以获取已保存照片的列表并确定列出的照片数量。我想要做的是 return 名称中包含文本 "Biological Hazards" 的照片数量。到目前为止,这是我的代码

getPhotoNumber(): void {
  this.storage.get(this.formID+"_photos").then((val) => {
    this.photoResults = JSON.parse(val);
    console.log("photoResults", this.photoResults);
    // photoResults returns 3 photos
      // Hazardscamera_11576868238023.jpg, 
      // Biological Hazardscamera_11576868238023.jpg,
      // Biological Hazardscamera_11576868351915.jpg
    this.photoList = this.photoResults.length;
    console.log("photoList", this.photoList); // returns 3
    this.photoListTwo = this.photoResults.includes('Biological Hazards').length; // I wish to return 2   
  }).catch(err => {
    this.photoList = 0;
  });
}

如有任何帮助,我们将不胜感激。

Xcode 日志

[

方法includes returns boolean表示数组是否包含值。你需要的是过滤你的数组和 return 之后的长度。 您需要替换行:

this.photoListTwo = this.photoResults.includes('Biological Hazards').length; 

由此:

this.photoListTwo = this.photoResults.filter(function(result) {return result.contains("Biological Hazards");}).length; 

此问题的快速解决方案(抱歉缺乏更好的格式,从手机发布):

const array = ["Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868351915.jpg"];

const filterBioHazards = (str) => /Biological Hazards/.test(str);

console.log(array.filter(filterBioHazards).length);
// Prints 2

一种方法是 .filter() 数组,然后计算该数组的长度。

this.photoListTwo = this.photoResults.filter(photoString => {
 return photoString === 'Biological Hazards' //or whatever comparison makes sense for your data
}).length;