自定义高阶filter函数返回布尔值而非符合条件单词的问题求助
问题解决:自定义Filter函数修正
你的问题出在myFilterFunction的逻辑上——当前它只是把回调函数返回的布尔值挨个塞进新数组,并没有根据布尔值筛选原数组的元素。不需要额外加代码,只要修改现有函数的循环逻辑就行。
修正后的代码
const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"]; // 修改后的高阶filter函数 let myFilterFunction = (arr) => (fn) => { const newArray = []; for (let i = 0; i < arr.length; i++) { // 先判断回调返回的结果,为true时才把原元素加入新数组 if (fn(arr[i])) { newArray.push(arr[i]); } } return newArray; }; // 调用方式不变 const printArray = myFilterFunction(wordArray)((word) => word.length >= 6); console.log("this array only contains words that are 6 letters or more: " + printArray);
关键修改点
- 去掉了直接push回调结果的逻辑,改成先判断回调返回的布尔值
- 只有当
fn(arr[i])返回true时,才将原数组的元素arr[i]添加到新数组中
输出结果
运行后控制台会输出:
this array only contains words that are 6 letters or more: script,function,javascript,python,coding
内容的提问来源于stack exchange,提问作者NewQode10
相关产品推荐
相关产品推荐

