javascript - 将两个回调函数合二为一
问题描述
这是问题...
“在标记为“在此处添加代码”的地方将代码添加到函数eitherCallback以实现所需的控制台日志。使用eitherCallback将两个回调合并为一个回调,然后将该回调传递给filterArray的结果应与只需将两个回调传递给上一个挑战中的任一过滤器。”
这是我知道可行的先前挑战的解决方案...
function eitherFilter(array, callback1, callback2) {
// ADD CODE HERE
const newArr = [];
for (let i = 0; i < array.length; i++) {
if (callback1(array[i]) || callback2(array[i])) {
newArr.push(array[i]);
}
}
return newArr;
}
// Uncomment these to check your work!
const arrOfNums = [10, 35, 105, 9];
const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
const over100 = n => n > 100;
console.log(eitherFilter(arrofNums, integerSquareRoot, over100)); // should log: [105, 9]
这是给出的代码...
function eitherCallback(callback1, callback2) {
// ADD CODE HERE
}
// Uncomment these to check your work!
function filterArray(array, callback) {
const newArray = [];
for (let i = 0; i < array.length; i += 1) {
if (callback(array[i], i, array)) newArray.push(array[i]);
}
return newArray;
}
const arrOfNums = [10, 35, 105, 9];
const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
const over100 = n => n > 100;
const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
console.log(filterArray(arrOfNums, intSqRtOver100)); // should log: [105, 9]
我对该怎么做感到困惑。谁能给我一些提示?我什至不知道如何开始回答它!
提前致谢...
解决方案
您不需要太多 - 您只需要创建eitherCallback
一个高阶函数,该函数将两个回调作为初始参数,并执行并返回您在此处执行的逻辑:
callback1(array[i]) || callback2(array[i])
喜欢:
const eitherCallback = (callback1, callback2) => x => callback1(x) || callback2(x);
// Uncomment these to check your work!
function filterArray(array, callback) {
const newArray = [];
for (let i = 0; i < array.length; i += 1) {
if (callback(array[i], i, array)) newArray.push(array[i]);
}
return newArray;
}
const arrOfNums = [10, 35, 105, 9];
const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
const over100 = n => n > 100;
const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
console.log(filterArray(arrOfNums, intSqRtOrOver100)); // should log: [105, 9]
推荐阅读
- react-native - 函数不是函数 - react-native
- java - 使用 Java & Gradle 从 github 构建一个 maven 项目
- angular - Angular 4:Viewchild 设置焦点
- java - 如何以编程方式关闭并重新启动应用程序?
- json - Jmeter在jmeter json提取器中提取空值
- python - 如何从文本文件创建复杂的字典?
- sonarqube - [Sonarqube][Java]Printf风格的格式字符串应该正确使用
- android - Gradle 正在构建,但我的 apk 没有构建。以下是调试报告
- react-native - 无法测试 react-native ./scripts/run-android-local-unit-tests.sh
- javascript - 如何确定我网站的 FCP?