问题是……
为函数eitherCallback添加代码"ADD CODE HERE">以实现所需的控制台日志。使用eitherCallback的结果将两个回调合并为一个回调,然后将这个回调传递给filterArray应该与简单地将两个回调传递到eitherFilter的结果相匹配。在上一个挑战."这是先前挑战的解决方案,我知道它有效…
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]
我不知道该做什么。有人能给我一些建议吗?我甚至不知道如何开始回答它!Thanks in advance…
您不需要太多-您所需要的只是使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]
你也可以试试:
function eitherCallback(callback1, callback2) {
// ADD CODE HERE
return (element, i, array) => {
//element representing array[i]
return callback1(element, i, array) || callback2(element, i, array);
}
}
这个想法是为eitherCallback返回一个在函数内调用的回调的真实值。同时,我相信"x"。在前面的解决方案中,从一定性能上表示参数array[i]、i和array。这是一种用x表示的更简洁的方式而不是重复。保持物品干燥。