【发布时间】:2019-10-27 07:43:07
【问题描述】:
我想:
创建一个函数 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 }
【问题讨论】:
-
因为它返回赋值的结果,即
boo * 2,即NaN -
第一个条件仅在最后一次调用时才被调用,因此此时 newObj 中没有存储任何值。
标签: javascript function object callback return