我有一种方法可以获取已保存照片的列表并确定列出的照片数量。我要做的是返回名称中包含“生物危害”文本的照片数量。到目前为止,这是我的代码
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日志
[
答案 0 :(得分:2)
一种方法是.filter()数组,然后计算该数组的长度。
this.photoListTwo = this.photoResults.filter(photoString => {
return photoString === 'Biological Hazards' //or whatever comparison makes sense for your data
}).length;
答案 1 :(得分:1)
对此的快速解决方案(很抱歉,缺少更好的格式,无法通过移动设备发布):
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
答案 2 :(得分:0)
方法includes
返回boolean
,以指示数组是否包含值。您需要过滤数组并在之后返回其长度。
您需要替换以下行:
this.photoListTwo = this.photoResults.includes('Biological Hazards').length;
通过这个:
this.photoListTwo = this.photoResults.filter(function(result) {return result.contains("Biological Hazards");}).length;