JavaScript:创建返回基于输入参数返回值或对象的函数的函数

时间:2019-06-12 18:18:55

标签: javascript function object callback return

我要:

创建一个函数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 }

1 个答案:

答案 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 }