gpt4 book ai didi

javascript - 如何正确地向局部函数添加参数?

转载 作者:行者123 更新时间:2023-11-29 10:01:23 26 4
gpt4 key购买 nike

我正在尝试通过函数中的给定 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 方法,因为它(我假设)在数组上进行不可见的迭代。

最佳答案

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);
});
}

如果需要,请不要犹豫,询问详细信息;)

关于javascript - 如何正确地向局部函数添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com