我正在尝试通过函数中的给定ID过滤数组,但是我不知道如何将ID添加到过滤方法中
function checkIdFilter(mediaObject, subCollectionId){
//mediaObject is allMedia[index??]
console.log("FILTERING ON " + subCollectionId);
return mediaObject.id == subCollectionId//check if mediaObject has certain ID here;
}
function searchMediaByCollection(subCollectionId) {
let filteredMedia = allMedia.filter(checkIdFilter);
// let filteredMedia = allMedia.filter(checkIdFilter(this.mo??, subCollectionId));
}
如您所见,我不知道如何正确地将ID传递给checkIdFilter方法,因为它(我认为)在数组上进行了不可见的迭代。
答案 0 :(得分:4)
filter
函数仅使用一个参数:当前对象,因此您必须将函数包装在另一个函数中,并使用闭包到达subCollectionId
。
function checkIdFilter(mediaObject, subCollectionId){
//mediaObject is allMedia[index??]
console.log("FILTERING ON " + subCollectionId);
return mediaObject.id == subCollectionId//check if mediaObject has certain ID here;
}
function searchMediaByCollection(subCollectionId) {
let filteredMedia = allMedia.filter(media => checkIdFilter(media, subCollectionId);
}
或
function searchMediaByCollection(subCollectionId) {
let filteredMedia = allMedia.filter(function(media) {
return checkIdFilter(media, subCollectionId);
});
}
如有需要,请随时询问细节;)