我要:
创建一个函数saveOutput,该函数接受一个函数(将接受一个参数)和一个字符串(将作为密码)。然后,saveOutput将返回一个行为与传入函数完全相同的函数,只是将密码字符串作为参数传入时除外。发生这种情况时,返回的函数将返回一个对象,该对象将以前传入的所有参数作为键,并将相应的输出作为值
我尝试了以下代码:
const saveOutput = (inputFunc, str) => {
let newObj = {};
return function (value) {
if (value === str){
return newObj[value] = inputFunc(value)
}
// return a function that behaves exactly like the passed-in function
else {
return inputFunc(value)
}
}
}
// Uncomment these to check your work!
const multiplyBy2 = function(num) { return num * 2; };
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2)); // should log: 4
console.log(multBy2AndLog(9)); // should log: 18
console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }
我的代码返回:
console.log(multBy2AndLog(2)); // returns 4
console.log(multBy2AndLog(9)); // returns 18
console.log(multBy2AndLog('boo')); // returns NaN
为什么我的第三个也是最后一个console.log应该返回NaN却应该返回:
{ 2: 4, 9: 18 }
答案 0 :(得分:1)
您必须将newObj
分配移至else
子句,并在newObj
时返回value === str
:
if (value === str){
return newObj;
}
// return a function that behaves exactly like the passed-in function
else {
newObj[value] = inputFunc(value);
return inputFunc(value);
}
实时示例:
const saveOutput = (inputFunc, str) => {
let newObj = {};
return function (value) {
if (value === str){
return newObj;
}
// return a function that behaves exactly like the passed-in function
else {
newObj[value] = inputFunc(value);
return inputFunc(value)
}
}
}
// Uncomment these to check your work!
const multiplyBy2 = function(num) { return num * 2; };
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2)); // should log: 4
console.log(multBy2AndLog(9)); // should log: 18
console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }